Backbone Routers: wait for data to be fetched first

前端 未结 2 1431
醉话见心
醉话见心 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:08

    I'm just checking in my .render() method that all required fields are filled, before using it. If it's not filled yet - i'm rendering an 'Loading...' widget.

    And all my views are subscribed to model changes, by this.model.bind('change', this.render, this);, so just after model will be loaded, render() will be called again.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题