javascript - Backbone.js - Not able to trigger an event in a collection -
i'm new javascript , backbone , came across error.
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 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(); } });
i error: unable property 'trigger' of undefined or null reference
. if
statement makes sure album
exists before triggering clear
. tried calling album.reset()
directly got same error. guess it's kind of scoping problem, please point me in right direction?
edit
re-reading code, assuming controller
valid instance , exists, , assuming controller.collectioninitialized
set true, calling method trigger
on variable album
value null.
using js hoisting rules, load function have written
load: function(albumid) { var album = null; if (controller.collectioninitialized == true) { console.log("reset"); album.trigger("clear"); } album = new album([], { title: albumid }); controller.trigger("collectioninit"); controller.trigger("switchalbum", albumid); }
maybe, above re-writing makes clear if controller.collectioninitialized
true
, album
local variable , reset null each time load function called.
what ever mechanism used enable global access controller
, use same means enable global access album
. not re-declare album
local function.
...
it may read more javascript variable , function hoisting.
Comments
Post a Comment