Last active
November 17, 2018 10:08
-
-
Save coderek/93e74dd5183814a76fa2 to your computer and use it in GitHub Desktop.
Implement filter collectionview for marionette
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* matchFilter | |
* @param {Object} term - key:val pairs that model need to match | |
* @returns {boolean} | |
*/ | |
Backbone.Model.prototype.matchFilter = function (conditions) { | |
return _.every(conditions, function (val, key) { | |
return this.get(key) === val; | |
}, this); | |
}; | |
var contr = Marionette.CollectionView.prototype.constructor; | |
Marionette.CollectionView = Marionette.CollectionView.extend({ | |
constructor: function () { | |
contr.apply(this, arguments); | |
this._filterConditions = null; | |
this.on('filter', this.filter); | |
this.listenTo(this.collection, 'sync', function () { | |
this.filter(this._filterConditions); | |
}); | |
}, | |
filter: function (conditions) { | |
// remember filter | |
this._filterConditions = conditions; | |
if (!conditions || !_.isObject(conditions)) { | |
this.children.each(function (v) { | |
v.$el.removeClass('hide'); | |
}); | |
return; | |
} | |
this.children.filter(function (childView) { | |
if (childView.model.matchFilter(conditions)) { | |
childView.$el.addClass('hide'); | |
} else { | |
childView.$el.removeClass('hide'); | |
} | |
}); | |
} | |
}); | |
// ======= test it ===== | |
var People = Backbone.Collection.extend({url: '/people'}); | |
var people = new People(); | |
var PeopleView = Marionette.ItemView.extend({ | |
tagName: 'li', | |
template: _.template('<%=name%> <strong><%=gender%></strong>') | |
}) | |
var PeopleList = Marionette.CollectionView.extend({ | |
tagName: 'ul', | |
itemView: PeopleView | |
}); | |
var list = new PeopleList({collection: people}); | |
var mainRegion = new Marionette.Region({el: '#main'}); | |
$(function () { | |
mainRegion.show(list); | |
$('body').on('change', 'input[type=checkbox]', function (ev) { | |
var isChecked = $(ev.target).prop('checked'); | |
if (isChecked) { | |
list.trigger('filter', {gender: 'F'}); | |
} else { | |
list.trigger('filter'); | |
} | |
}); | |
$('body').on('click', 'button#fetch', function () { | |
people.fetch(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment