From a449b17d51c326dcf7be04850a6d18c407000c4a Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Sat, 21 Dec 2013 17:28:03 -0600 Subject: [PATCH] HR-226 - CRM.Backbone.extendCollection - Add helper for representing "crmCriteria" as a full-fledged model --- js/crm.backbone.js | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/js/crm.backbone.js b/js/crm.backbone.js index 746ddaf7be..87c1c5cbc3 100644 --- a/js/crm.backbone.js +++ b/js/crm.backbone.js @@ -277,7 +277,7 @@ * }); * CRM.Backbone.extendCollection(ContactCollection); * - * // Use class + * // Use class (with passive criteria) * var c = new ContactCollection([], { * crmCriteria: {contact_type: 'Organization'} * }); @@ -285,8 +285,21 @@ * c.get(123).set('property', 'value'); * c.get(456).setDeleted(true); * c.save(); + * + * // Use class (with active criteria) + * var criteriaModel = new SomeModel({ + * contact_type: 'Organization' + * }); + * var c = new ContactCollection([], { + * crmCriteriaModel: criteriaModel + * }); + * c.fetch(); + * c.get(123).set('property', 'value'); + * c.get(456).setDeleted(true); + * c.save(); * @endcode * + * * @param Class CollectionClass * @see tests/qunit/crm-backbone */ @@ -299,6 +312,26 @@ return (this.crmCriteria) ? _.extend({}, this.crmCriteria) : {}; }, + /** + * Get an object which represents this collection's criteria + * as a live model. Any changes to the model will be applied + * to the collection, and the collection will be refreshed. + * + * @param criteriaModelClass + */ + setCriteriaModel: function(criteriaModel) { + var collection = this; + this.crmCriteria = criteriaModel.toJSON(); + this.listenTo(criteriaModel, 'change', function() { + collection.crmCriteria = criteriaModel.toJSON(); + collection.debouncedFetch(); + }); + }, + + debouncedFetch: _.debounce(function() { + this.fetch({reset: true}); + }, 500), + /** * Reconcile the server's collection with the client's collection. * New/modified items from the client will be saved/updated on the @@ -327,7 +360,9 @@ sync: CRM.Backbone.sync, initialize: function(models, options) { options || (options = {}); - if (options.crmCriteria) { + if (options.crmCriteriaModel) { + this.setCriteriaModel(options.crmCriteriaModel); + } else if (options.crmCriteria) { this.crmCriteria = options.crmCriteria; } if (origInit) { -- 2.25.1