我正在尝试将事件添加到集合中。我想在每次集合更改(新模型、模型属性更改等)时重新渲染 View 。这是我的代码:
var app = {}; // custom name space
// models
app.Group = Backbone.Model.extend({
url: '/group'
});
app.Category = Backbone.Model.extend({
url: '/category'
});
// collections
app.GroupList = Backbone.Collection.extend({
model: app.Group,
url: 'data/getGroups.php' // '/groups'
});
app.CategoryList = Backbone.Collection.extend({
model: app.Category,
url: 'data/getCategories.php' // '/categories'
});
app.groupList = new app.GroupList();
app.categoryList = new app.CategoryList();
// views
app.CategoriesView = Backbone.View.extend({
...
});
// bind events
app.GroupList.on('change reset add remove', app.CategoriesView.render);
app.CategoryList.on('change reset add remove', app.CategoriesView.render);
...但是,我在控制台中收到以下错误“TypeError:app.GroupList.on 不是函数”。我尝试对模型而不是集合执行相同的操作,但出现相同的错误 - “.on”不是函数。在文档中,“on”似乎至少属于模型,但正如前面提到的,这也不起作用。添加监听器的正确方法是怎样的?我应该在模型上还是在系列上这样做?
如果有人可以提供任何帮助,我们将不胜感激。谢谢
最佳答案
您只能将事件绑定(bind)到实例:
app.groupList.on(...);
同样,render
仅适用于 View 实例:
// views
app.CategoriesView = Backbone.View.extend({
...
});
var myView = new app.CategoriesView({
// somewhere in here you'll pass app.grouplist...
});
app.groupList.on('change reset add remove', myView.render);
关于javascript - 尝试使用 "on"函数将事件监听器添加到集合(或模型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21747789/