cen*_*cru 0 backbone.js backbone-events backbone-views
以下代码使得看起来好像在获取完成之前,AccItemList集合上的"reset"事件被触发.控制台的输出如下......
翻译
0
取
0
...所以在集合中有任何模型之前调用"render",这显然是错误的,但即使在fetch成功回调中也是如此令人困惑,集合中似乎没有任何模型.我也尝试在路由器初始化程序中实例化AccItemList集合,但这没有任何不同.我确定我错过了一些基本的东西,请帮助,这让我发疯!
$(function () {
var AccItem = Backbone.Model.extend({
defaults: {}
});
var AccItemList = Backbone.Collection.extend({
model: AccItem,
url: "/Dashboard/Accommodation",
parse: function (response) {
this.add(response.AccItems);
}
});
var AccListView = Backbone.View.extend({
el: $("#temp"),
initialize: function () {
_.bindAll(this, 'render', 'renderAccItem');
this.collection = new AccItemList();
this.collection.on('reset', this.render);
var that = this;
that.collection.fetch({
success: function () {
console.log("fetched");
console.log(that.collection.models.length);
}
});
},
render: function () {
var that = this;
console.log("rendering");
console.log(this.collection.models.length);
}
});
var App = Backbone.Router.extend({
routes: {
"": "index"
},
index: function () {
},
init: function () {
var accItemView = new AccListView();
}
});
var app = new App();
app.init();
});
Run Code Online (Sandbox Code Playgroud)
在AccItemList.parse,您手动添加模型,除了Backbone doc状态之外不返回任何内容
parse collection.parse(response)
只要服务器在fetch中返回集合的模型,Backbone就会调用parse.该函数传递给原始响应对象,并应返回要添加到集合中的模型属性数组.默认实现是无操作,只是通过JSON响应.如果您需要使用预先存在的API,或者更好地命名您的响应,请覆盖此项.请注意,之后,如果您的模型类已经具有解析函数,则将针对每个获取的模型运行它.
尝试
var AccItemList = Backbone.Collection.extend({
model: AccItem,
url: "/Dashboard/Accommodation",
parse: function (response) {
return response.AccItems;
}
});
Run Code Online (Sandbox Code Playgroud)
模拟代码和修改版本的小提琴:http://jsfiddle.net/nikoshr/Q25dp/
调用重置事件和成功回调的顺序取决于Backbone源中的实际实现.请参阅http://documentcloud.github.com/backbone/docs/backbone.html#section-98
var success = options.success;
options.success = function(resp, status, xhr) {
//reset call
collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
//custom success call
if (success) success(collection, resp);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2133 次 |
| 最近记录: |