Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackboneJs: how do i bootstrap my data in the page markup, and when do i assign them to my collections

So, building an application that uses multiple (2 for now) global collections, it is a catalog of both documents and patients, they have relations, but not as in, 1 document or a list of documents belonging to 1 patient, so they are in fact 2 separate collections,

my app is structured in a module system very similar to how it is described here: http://weblog.bocoup.com/organizing-your-backbone-js-application-with-modules

the backbone.js documentation says about bootstrapping, to do something like this,

<script>
  Accounts.reset(<%= @accounts.to_json %>);
</script>

that is within a Rails application, i would however need to do it differently in asp.net MVC3, most likely i would just print out my json string without the <%= %> which isn't razor view engine style)

but my question here is,

this Accounts.reset(...data...); is just floating somewhere in my markup, it is not in any way nicely structured in my module system, isn't there a way to nicely do this? where as i can get the data, from within my module?

and another side question, suppose i have a route in my backbone app http://example.com/#documents

and someone calls this link directly, will my app have the data ready (from the bootstrap) on time, before the route itself is executed?

like image 477
Sander Avatar asked Oct 25 '11 20:10

Sander


1 Answers

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.

like image 127
Derick Bailey Avatar answered Oct 02 '22 16:10

Derick Bailey