我正在尝试实现一个简单的应用程序,它能够获取给定 object_id
的集合。
来自服务器的 GET 响应
如下所示:
[
{object_id: 1, text: "msg1"},
{object_id: 1, text: "msg2"},
{object_id: 1, text: "msg3"},
.......
]
我的目标是:
当用户选择一个object_id
时呈现一个集合。
我的代码的起点如下:
this.options = {object_id: 1};
myView = new NeView(_.extend( {el:this.$("#myView")} , this.options));
我的问题是:
* 什么是最好的方法:
1) 在 MyModel
中设置 object_id 值
,以便
2) 在 MyCollection 中触发 fetch
然后
3) 触发 myView
中的 render
函数?* 或激活我的目标?
附言:
我的基本代码如下所示:
// My View
define([
"js/collections/myCollection",
"js/models/myFeed"
], function (myCollection, MyModel) {
var MyView = Backbone.View.extend({
initialize: function () {
var myModel = new MyModel();
_.bindAll(this, "render");
myModel.set({
object_id: this.options.object_id
}); // here I get an error: Uncaught TypeError: Object function (){a.apply(this,arguments)} has no method 'set'
}
});
return MyView;
});
// MyCollection
define([
"js/models/myModel"
], function (MyModel) {
var MyCollection = Backbone.Collection.extend({
url: function () {
return "http://localhost/movies/" + myModel.get("object_id");
}
});
return new MyCollection
});
//MyModel
define([
], function () {
var MyModel = Backbone.Model.extend({
});
return MyModel
});
最佳答案
您对 Backbone 内部结构的基本理解存在一些错误,即使不是根本性的错误。
首先,定义您的默认模型 idAttribute,这是用于标识您在集合中查找模型时使用的键
//MyModel
define([
], function () {
var MyModel = Backbone.MyModel.extend({
idAttribute: 'object_id'
});
return MyModel
});
在您的收藏中,无需按照您定义它的方式来定义您的 URL,您需要更改两件事,首先是为您的收藏定义默认模型,其次是坚持使用基础您收藏的网址
// MyCollection
define([
"js/models/myModel"
], function (MyModel) {
var MyCollection = Backbone.MyCollection.extend({
model: MyModel, // add this
url: function () {
return "http://localhost/movies
}
});
return MyCollection // don't create a new collection, just return the object
});
然后你的观点可能是这样的,但肯定不限于这种实现方式
// My View
define([
"js/collections/myCollection",
"js/models/myFeed"
], function (MyCollection, MyModel) {
var MyView = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.collection = new MyCollection();
this.collection.on('add', this.onAddOne, this);
this.collection.on('reset', this.onAddAll, this);
},
onAddAll: function (collection, options)
{
collection.each(function (model, index) {
that.onAddOne(model, collection);
});
},
onAddOne: function (model, collection, options)
{
// render out an individual model here, either using another Backbone view or plain text
this.$el.append('<li>' + model.get('text') + '</li>');
}
});
return MyView;
});
放轻松,循序渐进
我强烈建议您仔细查看 Backbone.js github wiki 上详尽的教程列表:https://github.com/documentcloud/backbone/wiki/Tutorials%2C-blog-posts-and-example-sites ...在添加 require.js 的额外复杂性之前尝试了解 Backbone 的基础知识
关于javascript - 为给定的 object_id 获取和呈现集合的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10632527/