gpt4 book ai didi

javascript - Backbone - 如何在获取集合时使用特定的扩展模型?

转载 作者:行者123 更新时间:2023-11-29 22:07:57 24 4
gpt4 key购买 nike

我正在尝试使用 Javascript、Requirejs 和 Backbonejs 创建一个 Wordpress 主题。

在索引路由中,我实例化了一个新的 postsCollection app.postsCollection = new Posts.Collection();,它将包含所有 WordPress 帖子。然后,我运行 .fetch() app.postsCollection.fetch( { success: ..., error: ... } );

这是我的modules/posts/collection.js 文件的代码:

define( function( require, exports, module ) {

"use strict";

var app = require( 'app' );
var PostModel = require( './model' );

var PostsCollection = Backbone.Collection.extend( {

model : PostModel,
url : app.jsonApi + "get_posts/",

parse: function( response ) {

return response.posts;

}

} );

module.exports = PostsCollection;

});

我的问题:

我想扩展 PostModel 定义 var ImagePostModel = PostModel.extend( { ... } );var GalleryPostModel = PostModel.extend( { ... } ) ;。然后,由于所收集数据的帖子类型(图像或图库),我想在获取时使用特定模型。我该怎么做?

最佳答案

一般来说,对于主干属性,您可以直接使用返回对象的函数而不是指定对象,例如,您可以提供一个返回事件哈希对象的函数。模型属性也是如此。

您可以使用一个基于某些条件返回适当的模型类型的函数,而不是为您的集合model指定一个模型。

来自documentation

A collection can also contain polymorphic models by overriding this property with a constructor that returns a model.

和提供的例子

var Library = Backbone.Collection.extend({

model: function(attrs, options) {
if (condition) {
return new PublicDocument(attrs, options);
} else {
return new PrivateDocument(attrs, options);
}
}

});

关于javascript - Backbone - 如何在获取集合时使用特定的扩展模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19844000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com