Backbone.js updating of models in a collection

后端 未结 5 1369
天涯浪人
天涯浪人 2021-01-30 11:47

Let\'s say you are building a Twitter clone with Backbone.js. You have a collection of tweets. Each tweet is obviously an instance of the Tweet model.

You create an inst

5条回答
  •  梦如初夏
    2021-01-30 12:29

    Lets assume that every one of your tweets has a unique identifier(if not, you should probably create one).

    You can structure your backend in such away that by default it gets you 10 latest tweets if you call http://your.site.com/tweets without any arguments.

    If you however call http://your.site.com/tweets?last_tweet_id=BLAblaBlA, it will give you 10 latest tweets that came after the last_tweet_id that you specified.

    You can override the code that gets the data from the backend into your Collection by implementing YourCollection.sync method.

    Reason: Backbone.Collection first tries to call Collection.sync and if its not implemented, it calls Backbone.sync function, so if you implement YourCollection.sync, it will be used. Here is the snippet from Backbone.Collection.fetch function:

    (this.sync || Backbone.sync)('read', this, success, error);
    

    so your sync would be something like

    var TweetCollection = Backbone.Collection.extend({
      model: TweetModel,
      sync: function(method, collection, success, error) {
        var requestData={};
        if(collection.length>0) {
            requestData.last_tweet_id=collection.last.id 
        }
        var params = {
            url:          "/tweet",
            type:         "POST",
            data:         requestData,
            success:      success,
            error:        error
        };
        $.ajax(params);
      }
    }
    

    You would have to override your collections parse function to make sure that the response is appended to the existing array of models.

提交回复
热议问题