我是一个骨干.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()));
}
});
更新:这是相应集合的代码
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');
}
});
更新#2:集合初始化和人口
App.Collections.roster = new App.Collections.Contact;
function getContacts() {
socketRequest('friends', function(data) {App.Collections.roster.reset(data)});
}
更新#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: ''
}
});
答案 0 :(得分:4)
您需要使用View.el属性才能使事件正常工作。
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');
},
render: function() {
;
}
});
App.Views.Contacts = Backbone.View.extend({
el: '#contacts',
initialize: function() {
this.collection = new App.Collection.Contact;
this.collection.bind('reset', this.render, this);
var that = this;
socketRequest('friends', function(data) {
this.reset(data);
});
},
render: function() {
$(this.el).html('put your template here');
this.collection.each(this.addOne, this);
return this;
},
addOne: function(contact) {
var view = new App.Views.Contact({model: contact});
contact.view = view; // in case you need the ref on the model itself
$(this.el).append(view.render().el);
}
});
App.Views.Contact = Backbone.View.extend({
el: '',
tagName: 'div',
events: {
'click': 'select',
},
select: function(event) {
console.log('contact selected');
},
render: function() {
$(this.el).html(htmltmplContact(this.model.toJSON()));
return this;
}
});
您的型号代码略有改进:
(注意我删除了视图创建,这很重要!)
App.Models.Contact = Backbone.Model.extend({
parse: function(c) {
c.id = c.token;
c.avatar = parseAvatar(c.avatar);
c.name = parseName(c);
return c;
},
defaults: {
username: ''
}
});
并开始行动:
App.Views.roster = App.Views.Contacts;