Skip to content

Instantly share code, notes, and snippets.

@mmun
Last active December 26, 2015 00:09
Show Gist options
  • Save mmun/7062576 to your computer and use it in GitHub Desktop.
Save mmun/7062576 to your computer and use it in GitHub Desktop.
Ember.computed.iterativeStringFilter = function(dependentKey, propertyKey, searchKey) {
var options = {
initialize: function (array, changeMeta, instanceMeta) {
instanceMeta.filteredArrayIndexes = new Ember.SubArray();
},
addedItem: function(array, item, changeMeta, instanceMeta) {
var itemValue = item.get(propertyKey),
searchValue = this.get(searchKey),
match = itemValue.indexOf(searchValue) > -1,
filterIndex = instanceMeta.filteredArrayIndexes.addItem(changeMeta.index, match);
if (match) {
array.insertAt(filterIndex, item);
}
return array;
},
removedItem: function(array, item, changeMeta, instanceMeta) {
var filterIndex = instanceMeta.filteredArrayIndexes.removeItem(changeMeta.index);
if (filterIndex > -1) {
array.removeAt(filterIndex);
}
return array;
},
// this hook would be called for dependent properties without one-at-time semantics
// `key` would contain the name of the key that changed
changedProperty: function(array, key, changeMeta, instanceMeta) {
if (key != searchKey) return;
var searchValue = this.get(searchKey),
// the previous value stored at this key would be stored in the changeMeta
prevSearchValue = changeMeta.previousValue;
// if our new search value is strictly more specific than
// the previous, then we only need to remove items that are
// already in the filter, instead of invalidating the entire
// filter.
if (searchValue.indexOf(prevSearchValue) > -1) {
for (var i = 0; i < array.length; i++) {
// ... remove item from filter if necesary ...
}
return array;
}
// else return undefined and recalculate the entire filter.
}
};
return Ember.arrayComputed(dependentKey, options);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment