Polling a Collection with Backbone.js

前端 未结 4 415
温柔的废话
温柔的废话 2021-01-30 02:49

I’m trying to keep a Backbone.js Collection up-to-date with what’s happening on the server.

My code is similar to the following:

var Comment = Backbone.M         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-30 03:25

    Make a duplicate collection. Fetch() it. Compare the two to find the deltas. Apply them.

          /*
           * Update a collection using the changes from previous fetch,
           * but without actually performing a fetch on the target 
           * collection. 
           */
          updateUsingDeltas: function(collection) {
            // Make a new collection of the type of the parameter 
            // collection.
            var newCollection = new collection.constructor(); 
    
            // Assign it the model and url of collection.
            newCollection.url = collection.url;
            newCollection.model = collection.model;
    
            // Call fetch on the new collection.
            var that = this;
            newCollection.fetch({
              success: function() {
                // Calc the deltas between the new and original collections.
                var modelIds = that.getIdsOfModels(collection.models);
                var newModelIds = that.getIdsOfModels(newCollection.models);
    
                // If an activity is found in the new collection that isn't in
                // the existing one, then add it to the existing collection.
                _(newCollection.models).each(function(activity) {
                  if (modelIds.indexOf(activity.id) == -1) { 
                    collection.add(activity);
                  }
                }, that);
    
                // If an activity in the existing colleciton isn't found in the
                // new one, remove it from the existing collection.
                _(collection.models).each(function(activity) {
                  if (newModelIds.indexOf(activity.id) == -1) {  
                    collection.remove(activity);  
                  }
                }, that);
    
                // TODO compare the models that are found in both collections,
                // but have changed. Maybe just jsonify them and string or md5
                // compare.
              }
            });
          },
    
          getIdsOfModels: function(models) {
            return _(models).map(function(model) { return model.id; });
          },
    

提交回复
热议问题