我一直在这个墙上撞墙几个小时.... 看了很多页面,我觉得我的脚本是正确的,但是我的集合没有触发add事件,并在fetch方法中传递了add:true。我可以绑定到重置事件,但add事件不会触发..
型号:
test.Models.AppBlock = Backbone.Model.extend({
defaults: {
AppID: null,
AppName: null,
AppDescription: null
},
idAttribute: "AppID"
});
收集:
test.Collections.AppBlock = Backbone.Collection.extend({
model: test.Models.AppBlock,
url: ApiPath + "apps/byuser",
Loading: false,
initialize: function () {
},
getAppBlocks: function () {
if (!this.Loading) {
this.Loading = true;
this.fetch({
data: JSON.stringify({
Token: test.Session.Token
}),
add: true, // OMG WTF ?!?!
type: 'POST',
dataType: 'json',
contentType: 'application/json',
cache: false,
success: this.getAppBlocksSuccess,
error: this.getAppBlocksError
});
}
},
parse: function (response) {
return response.Data;
},
getAppBlocksSuccess: function (that, response) {
},
getAppBlocksError: function (that, response) {
}
});
查看:
test.Views.DashboardLatestMain = Backbone.View.extend({
Loading: null,
initialize: function () {
this.template = _.template(test.Templates.DashboardLatestMain);
this.collection.bind('add', this.addAppBlock);
this.render();
},
render: function () {
$('#latest').prepend(this.template);
this.Loading = new test.Views.Loading({
el: '.main'
});
this.collection.getAppBlocks();
},
addAppBlock: function (appBlockModel) {
alert(appBlockModel); // no dice....
var appBlockView = new test.Views.AppBlock({
model: appBlockModel,
el: '#latest .main h3',
After: true
});
}
});
非常感谢任何帮助。
修改
从api返回的数据:
{
"Status":["1","OK"],
"Data":[{"AppID":1,"AppName":"test","AppDescription":"test"},
{"AppID":2,"AppName":"test","AppDescription":"test"}]
}
答案 0 :(得分:9)
在Backbone 0.9.9集合中,fetch
默认执行了reset
,仅触发了'重置'事件。在1.0中,fetch会执行update
(现在称为set
),并默认触发“添加”,“删除”和“更改”事件。
因此,要么更新到1.0,那么现有代码应该可行。或者,在update:true
电话中添加fetch
(您不需要add:true
,因为这是默认设置。)