【发布时间】:2013-10-17 20:50:05
【问题描述】:
我正在写一个简单的例子来学习 Backbone 和 Django-Tastypie。我正在使用 Backbone.js 1.0。
在控制台中,当我尝试notes = new NoteListView(); 时,我收到错误TypeError: Cannot call method 'bind' of undefined。
根据我在网上阅读的内容,我认为这是因为模板没有实例化。但是,模板缓存在视图上的模板调用中。所以,我很困惑。
也许我的想法完全错误,但应该发生的是绑定发生在已缓存的模板上,以便它可以执行设置并填充模板。
TastpieCollection 和 TasttypieModel 来自 http://paltman.com/2012/04/30/integration-backbonejs-tastypie/,这似乎工作得很好。
$(function() {
// Note: The model and collection are extended from TastypieModel and TastypieCollection
// to handle the parsing and URLs
window.Note = TastypieModel.extend({});
window.Notes = TastypieCollection.extend({
model: Note,
url: NOTES_API_URL
});
window.NoteView = Backbone.View.extend({
template: _.template($('#notes-item').html()),
initialize: function () {
_.bindAll(this, 'render');
this.model.bind('set', this.render);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
})
window.NoteListView = Backbone.View.extend({
template: _.template($('#notes-item-list').html()),
initialize: function () {
_.bindAll(this, 'render');
this.collection.bind('set', this.render);
},
render: function() {
var $notes,
collection = this.collection;
this.$el.html(this.template());
$notes = this.$('.notes');
collection.each(function(note){
var view = new NoteView({
model: note,
collection: collection
});
$notes.append(view.render().el);
});
return this;
}
})
})
那么,两个问题:
问题一:错误内容是什么,我该如何解决?
问题二:set 是reset 使用方式的新版本……对吗?
感谢您的帮助。
【问题讨论】:
-
model: Note应该是model: note。没有'set'事件,有'add'、'remove'和'change'事件。 -
我做了两处修改,Note to note 和 notes.append 放错了地方。两者都固定。
-
我对没有设置的事件感到困惑。我在这里从backbone.js 的文档中得到这个:backbonejs.org/#Collection-set
-
Collection#set文档说“所有适当的'add'、'remove'和'change'事件都会在这种情况发生时被触发”,这是因为set就是这样做的,它只是找出需要添加、删除和更改的组合。
标签: django backbone.js underscore.js backbone-views tastypie