1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | 1 1 1 25 25 29 29 1 28 1 8 1 33 33 37 37 1 8 1 1931 74 8 74 74 16 58 1 961 1 970 | // Marionette.bindEntityEvents & unbindEntityEvents // --------------------------- // // These methods are used to bind/unbind a backbone "entity" (collection/model) // to methods on a target object. // // The first parameter, `target`, must have a `listenTo` method from the // EventBinder object. // // The second parameter is the entity (Backbone.Model or Backbone.Collection) // to bind the events from. // // The third parameter is a hash of { "event:name": "eventHandler" } // configuration. Multiple handlers can be separated by a space. A // function can be supplied instead of a string handler name. (function(Marionette){ "use strict"; // Bind the event to handlers specified as a string of // handler names on the target object function bindFromStrings(target, entity, evt, methods){ var methodNames = methods.split(/\s+/); _.each(methodNames,function(methodName) { var method = target[methodName]; if(!method) { throwError("Method '"+ methodName +"' was configured as an event handler, but does not exist."); } target.listenTo(entity, evt, method, target); }); } // Bind the event to a supplied callback function function bindToFunction(target, entity, evt, method){ target.listenTo(entity, evt, method, target); } // Bind the event to handlers specified as a string of // handler names on the target object function unbindFromStrings(target, entity, evt, methods){ var methodNames = methods.split(/\s+/); _.each(methodNames,function(methodName) { var method = target[methodName]; target.stopListening(entity, evt, method, target); }); } // Bind the event to a supplied callback function function unbindToFunction(target, entity, evt, method){ target.stopListening(entity, evt, method, target); } // generic looping function function iterateEvents(target, entity, bindings, functionCallback, stringCallback){ if (!entity || !bindings) { return; } // allow the bindings to be a function if (_.isFunction(bindings)){ bindings = bindings.call(target); } // iterate the bindings and bind them _.each(bindings, function(methods, evt){ // allow for a function as the handler, // or a list of event names as a string if (_.isFunction(methods)){ functionCallback(target, entity, evt, methods); } else { stringCallback(target, entity, evt, methods); } }); } // Export Public API Marionette.bindEntityEvents = function(target, entity, bindings){ iterateEvents(target, entity, bindings, bindToFunction, bindFromStrings); }; Marionette.unbindEntityEvents = function(target, entity, bindings){ iterateEvents(target, entity, bindings, unbindToFunction, unbindFromStrings); }; })(Marionette); |