PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/js/lib/backbone-filtered-collection.js

https://github.com/encryb/encryb.github.io
JavaScript | 261 lines | 153 code | 28 blank | 80 comment | 27 complexity | 0a535936f5cdf51c038f3e997bba3897 MD5 | raw file
  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2013 Dmitriy Likhten
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. /* version 1.2.0 */
  21. (function(_, Backbone) {
  22. var defaultFilter = function() {return true;};
  23. /**
  24. * This represents a filtered collection. You can either pass a filter or
  25. * invoke setFilter(filter) to give a filter. The filter is identical to
  26. * that which is used for _.select(array, filter)
  27. *
  28. * false filter indicates no filtering.
  29. *
  30. * do not modify this collection directly via #add/#remove, modify the
  31. * underlying origModel.
  32. *
  33. * Events:
  34. * add - something was added (via filter or trickling from underlying collection)
  35. * remove - something was removed (via filter or trickling from underlying collection)
  36. * reset - the whole thing was reset
  37. * sort - same as reset, but via sort
  38. * filter-complete - filtering is complete -- very useful if you want to trigger a re-draw
  39. * of the whole collection
  40. */
  41. Backbone.FilteredCollection = Backbone.Collection.extend({
  42. collectionFilter: null
  43. ,defaultFilter: defaultFilter
  44. /**
  45. Default initializer.
  46. @param {Boolean} [models=false] - By default we must to use a falsy value here.
  47. @param {Object} data - Options.
  48. @param {Backbone.Collection} data.collection - Collection to be filtered
  49. @param {Function} data.collectionFilter - Filter to be applied to the collection.
  50. @constructor
  51. **/
  52. ,initialize: function(models, data) {
  53. if (models) throw "models cannot be set directly, unfortunately first argument is the models.";
  54. this.collection = data.collection;
  55. this.setFilter(data.collectionFilter);
  56. this._bindEvents();
  57. }
  58. /**
  59. * Replace the current underlying collection with a new one.
  60. * note: only a reset event will be fired.
  61. */
  62. ,resetWith: function(newCollection) {
  63. this.stopListening(this.collection);
  64. this.collection = newCollection;
  65. this.resetCollection();
  66. this._bindEvents();
  67. return this;
  68. }
  69. ,_bindEvents: function () {
  70. this.listenTo(this.collection, "add", this.addModel);
  71. this.listenTo(this.collection, "remove", this.removeModel);
  72. this.listenTo(this.collection, "reset", this.resetCollection);
  73. this.listenTo(this.collection, "sort", this.resortCollection);
  74. this.listenTo(this.collection, "change", this._modelChanged);
  75. this.listenTo(this.collection, "filter-complete", this._filterComplete);
  76. }
  77. ,_reset: function(options) {
  78. Backbone.Collection.prototype._reset.call(this, options);
  79. this._mapping = [];
  80. }
  81. ,add: function() {
  82. throw "Do not invoke directly";
  83. }
  84. ,remove: function() {
  85. throw "Do not invoke directly";
  86. }
  87. ,reset: function() {
  88. throw "Do not invoke directly";
  89. }
  90. ,_modelChanged: function(model, collection, options){
  91. options || (options = {});
  92. var ownIndexOfModel = this.indexOf(model);
  93. var self = this;
  94. if (this.collectionFilter(model)){
  95. // Model passed filter
  96. if (ownIndexOfModel < 0){
  97. // Model not found, add it
  98. var index = this.collection.indexOf(model);
  99. this._forceAddModel(model, {index: index});
  100. }
  101. // the model passes the filter and is already in the collection
  102. // therefore we want to indicate that the model has changed
  103. else {
  104. _.each(_.keys(model.changed), function(key) {
  105. self.trigger("change:" + key, model, model.changed[key], options);
  106. });
  107. this.trigger("change", model, this);
  108. }
  109. } else {
  110. // Model did not pass filter
  111. if (ownIndexOfModel > -1){
  112. this._forceRemoveModel(model, {index: ownIndexOfModel});
  113. }
  114. }
  115. if (! options.silent) {
  116. this._filterComplete();
  117. }
  118. }
  119. ,resortCollection: function() {
  120. // note: we don't need to do any filter work since sort
  121. // implies nothing changed, only order
  122. var newModels = [];
  123. var newMapping = [];
  124. var models = this.models;
  125. _.each(this.collection.models, function(model, index) {
  126. if (models.indexOf(model) >= 0) {
  127. newModels.push(model);
  128. newMapping.push(index);
  129. }
  130. });
  131. this.models = newModels;
  132. this._mapping = newMapping;
  133. this.trigger("sort", this);
  134. }
  135. ,resetCollection: function() {
  136. this._mapping = [];
  137. this._reset();
  138. this.setFilter(undefined, {silent: true});
  139. this.trigger("reset", this);
  140. }
  141. // this is to synchronize where the element exists in the original model
  142. // to our _mappings array
  143. ,renumberMappings: function() {
  144. this._mapping = []
  145. var collection = this.collection;
  146. var mapping = this._mapping;
  147. _(this.models).each(function(model) {
  148. mapping.push(collection.indexOf(model));
  149. });
  150. }
  151. ,removeModel: function(model, colleciton, options) {
  152. var at = this._mapping.indexOf(options.index);
  153. if (at > -1) {
  154. this._forceRemoveModel(model, _.extend({index: at}, options));
  155. }
  156. this.renumberMappings();
  157. }
  158. // the options.index here is the index of the current model which we are removing
  159. ,_forceRemoveModel: function(model, options) {
  160. this._mapping.splice(options.index, 1);
  161. Backbone.Collection.prototype.remove.call(this, model, {silent: options.silent});
  162. if (! options.silent) {
  163. this.trigger("remove", model, this, {index: options.index})
  164. }
  165. }
  166. ,addModel: function(model, collection, options) {
  167. if (this.collectionFilter(model)) {
  168. this._forceAddModel(model, _.extend(options || {}, {index: (options && options.at) || collection.indexOf(model)}));
  169. }
  170. this.renumberMappings();
  171. }
  172. // the options.index here is the index of the original model which we are inserting
  173. ,_forceAddModel: function(model, options) {
  174. var desiredIndex = options.index;
  175. // determine where to add, look at mapping and find first object with the index
  176. // great than the one that we are given
  177. var addToIndex = _.sortedIndex(this._mapping, desiredIndex, function(origIndex) { return origIndex; });
  178. // add it there
  179. Backbone.Collection.prototype.add.call(this, model, {at: addToIndex, silent: options.silent});
  180. this._mapping.splice(addToIndex, 0, desiredIndex);
  181. if (! options.silent) {
  182. this.trigger("add", model, this, {index: addToIndex})
  183. }
  184. }
  185. ,setFilter: function(newFilter, options) {
  186. options || (options = {});
  187. if (newFilter === false) { newFilter = this.defaultFilter } // false = clear out filter
  188. this.collectionFilter = newFilter || this.collectionFilter || this.defaultFilter;
  189. // this assumes that the original collection was unmodified
  190. // without the use of add/remove/reset events. If it was, a
  191. // reset event must be thrown, or this object's .resetCollection
  192. // method must be invoked, or this will most likely fall out-of-sync
  193. // why HashMap lookup when you can get it off the stack
  194. var filter = this.collectionFilter;
  195. var mapping = this._mapping;
  196. // this is the option object to pass, it will be mutated on each
  197. // iteration
  198. var passthroughOption = _.extend({}, options);
  199. this.collection.each(function(model, index) {
  200. var foundIndex = mapping.indexOf(index);
  201. if (filter(model, index)) {
  202. // if already added, no touchy
  203. if (foundIndex == -1) {
  204. passthroughOption.index = index
  205. this._forceAddModel(model, passthroughOption);
  206. }
  207. }
  208. else {
  209. if (foundIndex > -1) {
  210. passthroughOption.index = foundIndex == -1 ? this.length : foundIndex;
  211. this._forceRemoveModel(model, passthroughOption);
  212. }
  213. }
  214. }, this);
  215. if (! options.silent) {
  216. this._filterComplete();
  217. }
  218. }
  219. ,_onModelEvent: function(event, model, collection, options) {
  220. // noop, this collection has no business dealing with events of the original model
  221. // they will be handled by the original normal collection and bubble up to here
  222. }
  223. ,_filterComplete: function() {
  224. this.trigger("filter-complete", this);
  225. }
  226. });
  227. })(_, Backbone);