backbone.js 查看事件未触发
我是一个backbone.js n00b,所以请耐心等待。
我试图使用backbone.js 动态生成联系人列表,并为每个联系人附加一个 onclick 事件处理程序,但无济于事。我的视图渲染良好,但单击事件未注册。这是我的代码:
App.Views.Contact = Backbone.View.extend({
initialize: function() {
this.render();
},
events: {
'click': 'select',
},
select: function(event) {
console.log('contact selected');
},
render: function() {
$('#contacts').append(tmplContact(this.model.toJSON()));
}
});
UPDATE:这是相应集合 UPDATE #2 的代码
App.Collections.Contact = Backbone.Collection.extend({
initialize: function() {
this.bind('reset', function() {
console.log('COLLECTION RESET');
});
},
model: App.Models.Contact,
comparator: function(model) {
return model.get('name');
}
});
:集合初始化和填充
App.Collections.roster = new App.Collections.Contact;
function getContacts() {
socketRequest('friends', function(data) {App.Collections.roster.reset(data)});
}
UPDATE #3:模型定义
App.Models.Contact = Backbone.Model.extend({
initialize: function() {
this.set({id: this.get('token')});
this.set({avatar: parseAvatar(this.get('avatar'))});
this.set({name: parseName(this.toJSON())});
this.set({view: new App.Views.Contact({model: this})});
},
defaults: {
username: ''
}
});
I am sort of a backbone.js n00b so please bear with me.
I am trying to dynamically generate a list of contacts using backbone.js, and attach an onclick event handler to each, to no avail. My views are rendering fine, but click event does not register. Here is my code:
App.Views.Contact = Backbone.View.extend({
initialize: function() {
this.render();
},
events: {
'click': 'select',
},
select: function(event) {
console.log('contact selected');
},
render: function() {
$('#contacts').append(tmplContact(this.model.toJSON()));
}
});
UPDATE: here is the code for the corresponding collection
App.Collections.Contact = Backbone.Collection.extend({
initialize: function() {
this.bind('reset', function() {
console.log('COLLECTION RESET');
});
},
model: App.Models.Contact,
comparator: function(model) {
return model.get('name');
}
});
UPDATE #2: collection initialization and population
App.Collections.roster = new App.Collections.Contact;
function getContacts() {
socketRequest('friends', function(data) {App.Collections.roster.reset(data)});
}
UPDATE #3: model definition
App.Models.Contact = Backbone.Model.extend({
initialize: function() {
this.set({id: this.get('token')});
this.set({avatar: parseAvatar(this.get('avatar'))});
this.set({name: parseName(this.toJSON())});
this.set({view: new App.Views.Contact({model: this})});
},
defaults: {
username: ''
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用 View.el 属性才能使事件正常工作。
对模型代码的一个小改进:
(请注意,我删除了视图创建,这很重要!)
并开始:
You need to use the View.el property in order to get the events working.
a small improvement to your model code:
(notice that i removed the view creation, this is important!)
and to kick things off: