【发布时间】:2013-04-03 13:36:41
【问题描述】:
在这个问题上,我已经用头撞墙好几个小时了...... 看了很多页,我觉得我的脚本是正确的,但是我的集合没有触发 add 事件,add: true 在 fetch 方法中传递。我可以绑定到重置事件,但添加事件不会触发..
型号:
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"}]
}
【问题讨论】:
-
我们能否提供更多关于您调用返回的信息的信息?模型被添加到集合中,但没有触发“添加”事件?
-
您使用的是 BB 1.0 吗?如果没有,您需要使用
update:true,因为在 1.0 之前默认是重置而不是更新,这只会触发“重置”事件而不会触发“添加”事件。 -
@MikaelHärsjö 我不明白你的意思。他在从服务器获取数据,他为什么要使用 set?
-
啊,是的,我也会添加数据。我确实成功地取回了数据,并且集合包含两个模型。我想我正在使用骨干〜.9,但我会尝试更新:真正的解决方案。
-
@KennyThompson
this.collection.bind('add', this.addAppBlock);是错字吗?您的视图不属于任何集合,它的模型属于 (this.model.collection...)。