我是JavaScript和Backbone的新手,我遇到了这个错误。Backbone.js - 无法触发集合中的事件
Router = Backbone.Router.extend({
routes: {
":albumID": "load"
},
load: function (albumID) {
if (controller.collectionInitialized == true) {
console.log("RESET");
album.trigger("clear");
}
var album = new Album([], {
title: albumID
});
controller.trigger("collectionInit");
controller.trigger("switchAlbum", albumID);
}
});
Controller = Backbone.Model.extend({
currentAlbum: "",
collectionInitialized: false,
initialize: function() {
console.log("controller is initialized");
this.on("switchAlbum", function (newAlbum) {
this.currentAlbum = newAlbum;
});
this.on("collectionInit", function() {
this.collectionInitialized = true;
});
}
});
Album = Backbone.Collection.extend({
initialize: function (models, options) {
this.on("clear", this.clear);
},
clear: function() {
this.reset();
this.off();
}
});
我收到此错误:Unable to get property 'trigger' of undefined or null reference
。在触发clear
之前,if
声明确保album
已经存在。之前我尝试直接拨打album.reset()
,但得到相同的错误。我的猜测是这是某种范围的问题,有人可以请我指出正确的方向吗?
但是,如果'专辑'已经被创建,if语句确保它只触发'clear'。这不重要吗? – Dmitry 2013-05-08 16:38:42
@DimaShabatin实际上,我根据我对Javascript的了解(我不曾碰巧使用过Backbone)。你在哪里定义'collectionInit'和'collectionInitialized'? – 2013-05-08 16:48:58
只需在帖子中添加更多代码即可 – Dmitry 2013-05-08 17:13:14