Backbone Routers: wait for data to be fetched first

前端 未结 2 1430
醉话见心
醉话见心 2021-02-08 05:37

I think I don’t quite get the idea behind the proper usage of Backbone routers. Here’s what I’ve got:

I have some data that I fetch from the server when the page loads a

2条回答
  •  梦谈多话
    2021-02-08 06:09

    You can define your router ahead of time; it won't do anything until you call Backbone.History.start().

    You can bind the "reset" event on your collection to start history like this:

    my_collection.bind("reset", _.once(Backbone.History.start, Backbone.History))
    

    Then the router will start doing stuff when your collection is fully loaded. I'm not sure if this is exactly what you're looking for (since you mentioned having a variable number of collections).

    I have a similar situation, except that I know in advance which collections I want to have loaded before I start routing. I added a startAfter method to my Router, like so:

      window.Workspace = new (Backbone.Router.extend({
        . . .
        startAfter: function(collections) {
          // Start history when required collections are loaded
          var start = _.after(collections.length, _.once(function(){
            Backbone.history.start()
          }))
          _.each(collections, function(collection) {
            collection.bind('reset', start, Backbone.history)
          });
        }
      }));
    

    and then after I've setup my collections

      Workspace.startAfter([collection_a, collection_b, ...])
    

    This could be adapted to work with standalone models too, although I think you'd need to bind to something other than the 'reset' event.

    I'm glad I read your example code, the use of _.once and _.defer pointed me in the right direction.

提交回复
热议问题