I’m building a single page app with Backbone and Requirejs.
For now I’ve been returning a new instance from my module files, ending the files with:
return new moduleName;
This worked ok until I had to pass arguments to the initialize method of a collection. Since the initialize is called when the instance is created, I took the “new” away from the return statement.
return mymoduleName;
And instantiated the collection with parameters in my router:
myCollection = new library({paramname: "value"});
This indeed creates an instance of “library” – a collection introduced in my router’s define block, but how do I pass it to the view responsible of rendering it?
My view class has the same dependency in its define block and in its initialize I bind it to the collection’s reset:
this.collection = library;
_.bindAll(this, 'render');
this.collection.bind('reset', this.render);
This worked before taking away the “new” from the collection class (which on retrospective makes no sense at all!) but now the view never gets rendered because it was instantiated in the router – how do I pass that same instance to the view?
Don’t set the collection in its initialize method, but wherever you instantiate your view (in your case, the router).
If
myCollectionis a variable you need to access from other places as well, you can set it on the router (myRouter.myCollection = ...), you could create a model that holds global objects (MyAppGlobals) or you could simply have a global variable (not recommended).