Hacker News new | ask | show | jobs
by littlejim84 5243 days ago
This is nice to have it in one place, but I still not sure I like bootstrapping model data that way. Does anyone else find it a bit messy? Also, I'm using AMD/Require.js throughout my Backbone apps, so how could I bootstrap the model data in that manner, and still have access to it inside my modules?
4 comments

So, the reason why you want to bootstrap the models you need for an initial render, directly into the page ... instead of doing this:

    myApp.init = function() {
      Books.fetch();
      Authors.fetch();
      Notes.fetch();
      ...
    };
... is because, all else being equal, it will noticeably improve the speed of your initial page load. Instead of N separate HTTP requests, all of your model data is available in the same HTTP request that fetches the HTML. Put the bootstrap at the bottom of your page, and you're in pretty good shape.
Depending on the other content of the page and the nature of your traffic/user data, it might make more sense to take advantage of caching by making the initial loaded resource (the HTML file) completely static and loading the bootstrapped data in a single separate request.
Yes, absolutely. If the initial HTML page is heavy, and can be cached for all users, then separate makes sense. If the initial HTML page is light, or user-specific (the usual case for a backbone app) then bootstrapping in a single HTTP request makes sense.
In django it doesn't seem particularly messy. Using the django dynamicresponse library:

    from dynamicresponse.emitters import JSONEmitter

    @register.filter
    def serialize_to_json(obj):
        emitter = JSONEmitter(obj, {}, None)
        return emitter.render()
In the template script tag:

    var myObj = new MyObject({{python_object|serialize_to_json}});
    var myObjView = new MyObjectView({ model: myObj });
It then renders just as if you loaded it via an api call.
You can define a requirejs module that just consists of data: http://requirejs.org/docs/api.html#defsimple. Then in your app incantation (main.js for requirejs stuff), load this module and pass it to your app instance.

If you feel weird about loading data as a js file, there is also a requirejs plugin for loading raw json files as a module: https://github.com/millermedeiros/requirejs-plugins

The way I've done this in the past is:

1. Initialize views without models, hidden.

2. Make your 'top-level' view bind to a collections 'reset' event that fires once the model is loaded. At that stage you can give instances of the loaded models to whatever views need them and they can redraw themselves, either by calling a method on them directly or because they're listening for some event that you trigger.