Backbone.js updating of models in a collection

后端 未结 5 1319
天涯浪人
天涯浪人 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

    Currently, out of the box, no.

    The technique I use is the following. You have your TweetCollection that extend Backbone.Collection and it has a classic REST url like "/tweets" . Your backend is sending only the 10 latest record (or page 1). To get page 2 you would use a url like "/tweets?page=2" and the backend would send the next 10 tweets. The question is really: how do you keep old record while fetching new one?

    I use 2 collections:

    • The first one is the one used to render the tweets on the screen. It is a normal TweetCollection.
    • The second one is the one used to get the pages from the server. Let's call it TweetPageCollection.

    TweetPageCollection extends TweetCollection with the following url:

     page: 1,
     url : function(){ return "/tweets?page=" + this.page; }
    

    Now in your controller code you can do something like this:

    initialize: function(){
      this.tweets = new TweetCollection();
      this.pages = new TweetPageCollection();
      this.pages.bind("refresh", this.newPageReceived);
    
      this.pages.page = 1;
      this.pages.fetch();
    
      this.tweet_list_view = new TweetListView({model: this.tweets});
    },
    getNextPage: function(){
      this.pages.page++;
      this.pages.fetch();
    },
    newPageReceived : function(page){
      // here you can check that the tweet is not already in the tweets collections
      this.tweets.add(page.toArray());
    }
    ...
    

    Now when you want to fetch new tweets, you call getNextPage() and when the XHR will succeed your view will be refreshed.

    Same principles can be applied to refetch the latest tweets. 2 collections, 1 fetching, the other gathering fetches.

提交回复
热议问题