我已经定义了一个视图绑定到集合。
1)当我初始化View时,会执行对集合的提取调用 2)如果我查看获取请求的结果,那就没问题了 3)我想触发这个更改(在myCollection中)来调用render函数但它不起作用。
以下是我的代码的一部分:
define([
"MyCollection",
"!text/template"
], function (myCollection, myTemplate) {
var myView = Backbone.View.extend({
initialize: function ()
{
myCollection.bind('change', this.render); // why the render is not called when
// I perform the fetch even if the data is correctly loaded?
myCollection.fetch(); // it works
},
render: function ()
{
// some code
this.$el <-- undefined
}
});
return myView;
});
如果我使用
1)
initialize: function ()
{
myCollection.bind('reset', this.render); // this.$el <-- undefined in render call, Why?
myCollection.fetch(); // it works
}
2)
myCollection.fetch({
success: function () {
that.render(); // <-- here the $el is defined and it works, Why myCollection.bind('reset', this.render); not??
// it seems to me that when I use reset the render function is called before the this.$el is defined
}
});
答案 0 :(得分:1)
您必须收听reset
事件,而不是change
事件。
这样:
myCollection.bind('reset', this.render, this);
答案 1 :(得分:1)
Backbone会触发"reset" event,而不是成功完成fetch()后的更改事件
var myView = Backbone.View.extend({
initialize: function ()
{
myCollection.bind('reset', this.render);
myCollection.fetch(); // it works
},
render: function ()
{
// some code
}
});