BackboneJs: how do i bootstrap my data in the page markup, and when do i assign them to my collections
I tend to setup application
objects - an object that encapsulates all of the code needed to start my application. I then take parameters into that object's constructor, so that they can be used by the app object. Passing pre-loaded JSON data into the app object is one of the things I do, to keep the code sane and encapsulated.
It goes something like this, usually:
MyApp = (function(Backbone, _){ var MyModel = Backbone.Model.extend({}); var MyCollection = Backbone.Collection.extend({ model: MyModel }); var MyView = Backbone.View.extend({ initialize: function(){ this.collection.bind("reset", this.render, this); }, render: function(){ // do stuff with the collection here } }); var myApp = function(initialModels){ this.start = function(){ this.models = new MyCollection(); this.myView = new MyView({collection: this.models}); this.models.reset(initialModels); }; }; return myApp;})(Backbone, _);
And then in my page that needs to start up the app, I do this:
<script language="javascript"> var myApp = new MyApp(<%= mymodels.to_json %>); myApp.start();</script>
That's the rails version of course. Just replace the <%= ... %>
with your version for the Razor syntax in ASP.NET MVC.
if on Rails: in addition to Dericks answer you might want to use Gon to "get your Rails variables in your js".
then you would initialize your app like that:
<script language="javascript"> var myApp = new MyApp(gon.mymodels); myApp.start();</script>
The excellent example from Derick! For MVC 3+ use this syntax:
<script language="javascript"> var myApp = new MyApp( @Html.Raw(Json.Encode(Model)) ); myApp.start();</script>