Search code examples
restbackbone.jscreation

Router, model, or view, which one is the initiator


I am trying to be as lazy loading as possible,

But, I am puzzle on how to start, here is my "sequenced comprehension":

Objective: Create a contacts page with contacts existing on the server

  • Step1.0: To use the router: the <div id="contacts"> must exists to trigger a rule, so I stepped back to (Step0.9),
  • Step0.9: Created this div in the body. Fine, the router find the #contacts, Oh, but this is a view, ok, stepped back to (Step0.8).
  • Step0.8: Erase the div created in the body and replace it by a view instead:
contactsView = Backbone.View.extend 
tagName: 'div',
id: 'contacts'

To be lazy loading, this view should only be created when the #contact is trigger in my router table, but I just removed it from by body, it does exist anymore, I am back to Step1.0 ???

Some tutorials found, shows global variable settings... Please, how the general scenario using a router, a view, their models, and collection should proceed (no code is necessary for an answer, just one line for each steps) ?

I know there can be multiples ways, but what is the most common backbone step strategy to create elements.

Thanks in advance.


Solution

  • I'm not 100% sure I understood you correctly. If I didn't please let me know in the comments.

    There seems to be some confusion in your question regarding the usage of Backbone.Router in general. When the router maps a route to URL fragment #contacts, that has nothing to do with a DOM element with the id #contacts. The hash sign simply happens to be the identifier for an URL fragment and id CSS selector, but that's where the similarity ends.

    Typically my router looks something like this:

    var AppRouter = Backbone.Router.extend({
      routes: {
        contacts: "contactList"
      },
      contactList: function() {
        var contacts = new ContactCollection();
        var view = new ContactListView({collection:contacts});
        view.render().$el.appendTo("#contacts");
      }
    });
    

    Notice that the #contacts element doesn't need to be called that. You can call it #pony, or you can render the view directly to the document body if you want.

    So in these terms the workflow is:

    1. Router gets hit
    2. Collection is initialized
    3. View is rendered