【发布时间】:2012-07-28 13:06:47
【问题描述】:
我是第一次学习 Backbone.js,但在尝试从触发(或从视图中识别何时触发)获取自定义事件时遇到问题?
您可以在此处查看我的集合代码:https://github.com/Integralist/Backbone-Playground/blob/master/Assets/Scripts/App/main.js#L72-86,它在初始化时会触发自定义 collection:init 事件。
var Contacts = Backbone.Collection.extend({
model: Contact,
initialize: function(){
this.trigger('collection:init');
this.bind('add', this.model_added, this);
},
model_added: function(){
console.log('A new model has been created so trigger an event for the View to update the <select> menu');
}
});
但稍后在我正在监听该事件的视图中,我无法让函数 populate 触发:https://github.com/Integralist/Backbone-Playground/blob/master/Assets/Scripts/App/main.js#L90-107
var ContactsView = Backbone.View.extend({
initialize: function(){
console.log(contacts.models, 'get initial model data and populate the select menu?');
},
events: {
'collection:init': 'populate',
'change select': 'displaySelected'
},
populate: function(){
console.log('populate the <select> with initial Model data');
},
displaySelected: function (event) {
console.log('get model data and display selected user', event);
}
});
任何想法我做错了什么?
【问题讨论】:
-
嗨,视图是否通过构造函数接收集合?在视图内部的初始化方法期间,您是否订阅了这样的事件
this.collection.on("init",this.populate)
标签: backbone.js