Search code examples
javascriptbackbone.jsviewmodelurl-routing

Backbone router, view & model cooperation


I have the View containing some button. When that View becomes activated it should take the some URL parameter (in my case -- site id) and set it to the button attribute "data-site_id". There is a router too in the app. But I don't know how to implement it with the best way. Till now I see 3 supposed solutions:

  1. Extract site id from URL hash. URL is build by such a pattern:

    "sites/edit/:id(/:tab)": "editSite",

the question is -- may I use here a router itself (and, if yes then how?) or can not, and should parse it with common JS way? Of course, router & view are two different objects and located in different files/scopes.

  1. Save the site_id in model. But I'm not sure how to store it from router. I think I can create an instance of model, set it as variable under router scope and then treat it as usual, something like this:
(function(app, $, config, _) {

    var Model = new app.modelName();

    var Router = app.Router = Backbone.Router.extend({
        routes: {
            "": "start",
        //....
        "sites/edit/:id(/:tab)": "editSite",
        //...
    },
    //....

    editSite: function(id, tab){
        Model.set('site_id', id);
    }

  //.... 
})(window.Application, jQuery, window.chatConfig, _);

after that I can extract the site id from model in any time I want

  1. Assign a data-site_id attribute to the button just from the router. But this doesn't look as a best practice, right?

So what is your advice?


Solution

  • Your second suggested solution makes the most sense, you could then instantiate your view passing that model to the constructor.

    See http://backbonejs.org/#View-constructor