我正在将Backbone.js 1.1.2与jQuery 1.11一起使用。
我想我缺少了一些非常简单的东西。
我已经建立了一个模型:Contact
和一个集合:ContactList
。
我成功地ContactView
使用从中获得的模型渲染视图ContactList.fetch()
但是,当我尝试在视图初始值设定项中绑定更改事件时:
this.model.on('change', this.render, this);
...我得到:
backbone Uncaught TypeError: Object #<Object> has no method 'on'
因此,我回到文档中进行阅读,并阅读了.on()
其中的内容Backbone.Events
,并以某种方式需要扩展我的模型以使用此功能(以及为什么这不属于模型的现成功能的一部分??)
我试过宣布
_.extend(this, Backbone.Events);
...ContactView
声明绑定之前在initialize函数中,但没有骰子。
我需要怎么做才能使Backbone.Events功能正常工作?
更新:所有相关代码(sans模板)
var Contact = Backbone.Model.extend({
defaults: {
FirstName: '',
...[etc]
},
initialize: function() {
}
});
var ContactList = Backbone.Collection.extend({
model: Contact,
url: '/api/Contacts/getall'
});
var ContactView = Backbone.View.extend({
initialize: function() {
this.render();
this.model.on('change', this.render, this);
},
render: function () {
var template = _.template($('#contact_template').html(), this.model);
this.$el.html(template);
}
});
var contactList = new ContactList();
contactList.fetch({
success: function (collection, response, options) {
contactList.models.forEach(function (m) {
var $el = $('<li />')
.addClass('adminItem clearfix')
.appendTo($('#contactList'));
new ContactView({ el: $el, model: m.attributes });
});
}
});
这条线是麻烦的根源
new ContactView({ el: $el, model: m.attributes });
m.attributes
是一个普通的js对象。您想传递实际的模型对象:
new ContactView({ el: $el, model: m});
并且由于集合中包含下划线方法,因此您应该可以对此简化一些:
contactList.each(function (m) {
var $el = $('<li />')
.addClass('adminItem clearfix')
.appendTo($('#contactList'));
new ContactView({ el: $el, model: m});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句