Guest User

Untitled

a guest
Oct 11th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. Backbone.BaseCollection = Backbone.Collection.extend({
  2. // Holds id of locally deleted items we ignore if we
  3. // 'freshen' the collection and changes haven't propagated yet.
  4. _localDeletedIds: [],
  5. // Take an array of raw objects
  6. // If the ID matches a model in the collection, set that model
  7. // If the ID is not found in the collection, add it
  8. // If a model in the collection is no longer available, remove it
  9. //
  10. // Keeps local changes, in case we've added things in the meantime.
  11. freshen: function(objects) {
  12. var model;
  13. // Mark all for removal, unless local only change
  14. this.each(function(m) {
  15. if (!m.isNew()) m._remove = true;
  16. });
  17. // Apply each object
  18. _(objects).each(function(attrs) {
  19. model = this.get(attrs.id);
  20. if (model) {
  21. model.set(attrs); // existing model
  22. delete model._remove
  23. } else {
  24. // add new models, accounting for local deletions
  25. var locallyDeleted = _.find(this._localDeletedIds,
  26. function(id){ return id == attrs.id });
  27. if (!locallyDeleted) this.add(attrs);
  28. }
  29. }, this);
  30. // Now check for any that are still marked for removal
  31. var toRemove = this.filter(function(m) {
  32. return m._remove;
  33. })
  34. _(toRemove).each(function(m) {
  35. this.remove(m);
  36. }, this);
  37. this.trigger('freshen', this);
  38. },
  39. remove: function(models, options) {
  40. models = _.isArray(models) ? models.slice() : [models];
  41. for (i = 0, l = models.length; i < l; i++) {
  42. if (models[i].id) this._localDeletedIds.push(models[i].id);
  43. }
  44. return Backbone.Collection.prototype.remove.call(this, models, options);
  45. }
  46. });
Add Comment
Please, Sign In to add comment