backbone.js view renders before model fetch

前端 未结 5 1008
自闭症患者
自闭症患者 2021-01-05 15:51

I\'m trying to make a small backbone.js app, but struggle with the order of things.

In my html file, I have two script blocks in the header:



        
5条回答
  •  暖寄归人
    2021-01-05 16:21

    You can also take advantage of the deferred object http://api.jquery.com/category/deferred-object/ that Backbone.Model.fetch() returns, like this:

    window.MyModel = Backbone.Model.extend({
       url: '/mymodel'
    });
    
    //when the model is fetched, store a reference to the jQuery deferred object
    window.MyModelFetch = window.MyModel.fetch();
    
    window.MyModelView = Backbone.View.extend({
        template: _.template($('#mymodel-template').html()), 
    
        initialize: function () {
            _.bindAll(this, 'render');
        },
    
        render: function () {
            //reference the deferred object and use 'done' method 
            //to register a callback after complete
            window.MyModelFetch.done(function(){
                 var renderedContent = this.template(this.model.toJSON());
                 $(this.el).html(renderedContent);
                 return this;
            }
        }
    });
    

    You may want to create an extension of the backbone model that stores a deferred object on your model that you can reference, like this:

     Backbone.DeferrableModel = Backbone.Model.extend({
          fetch: function(){
               this.fetching = Backbone.Model.prototype.fetch.apply(this, arguments);
               return this.fetching;
          }
     });
    

    Then in your view render method, you can just say this:

      render: function () {
            //the deferred reference is now directly referenced from your model
            this.model.fetching.done(function(){
                 var renderedContent = this.template(this.model.toJSON());
                 $(this.el).html(renderedContent);
                 return this;
            }
        }    
    

    It can be very handy to use an extended model and follow this pattern throughout your backbone application.

提交回复
热议问题