mirror of
https://github.com/jashkenas/backbone.git
synced 2026-04-30 03:00:06 -04:00
Fixes #1456. Enhances Backbone.Events to support jQuery-style event maps, in 'on' and 'off'.
This commit is contained in:
14
backbone.js
14
backbone.js
@@ -81,6 +81,13 @@
|
||||
// Bind one or more space separated events, `events`, to a `callback`
|
||||
// function. Passing `"all"` will bind the callback to all events fired.
|
||||
on: function(events, callback, context) {
|
||||
if (_.isObject(events)) {
|
||||
for (key in events) {
|
||||
this.on(key, events[key], callback);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
var calls, event, list;
|
||||
if (!callback) return this;
|
||||
|
||||
@@ -99,6 +106,13 @@
|
||||
// with that function. If `callback` is null, removes all callbacks for the
|
||||
// event. If `events` is null, removes all bound callbacks for all events.
|
||||
off: function(events, callback, context) {
|
||||
if (_.isObject(events)) {
|
||||
for (key in events) {
|
||||
this.off(key, events[key], callback);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
var event, calls, list, i;
|
||||
|
||||
// No events, or removing *all* events.
|
||||
|
||||
@@ -17,7 +17,7 @@ $(document).ready(function() {
|
||||
|
||||
test("binding and triggering multiple events", 4, function() {
|
||||
var obj = { counter: 0 };
|
||||
_.extend(obj,Backbone.Events);
|
||||
_.extend(obj, Backbone.Events);
|
||||
|
||||
obj.on('a b c', function() { obj.counter += 1; });
|
||||
|
||||
@@ -35,6 +35,38 @@ $(document).ready(function() {
|
||||
equal(obj.counter, 5);
|
||||
});
|
||||
|
||||
test("binding and triggering with event maps", function() {
|
||||
var obj = { counter: 0 };
|
||||
_.extend(obj, Backbone.Events);
|
||||
|
||||
var increment = function() {
|
||||
this.counter += 1;
|
||||
};
|
||||
|
||||
obj.on({
|
||||
a: increment,
|
||||
b: increment,
|
||||
c: increment
|
||||
}, obj);
|
||||
|
||||
obj.trigger('a');
|
||||
equal(obj.counter, 1);
|
||||
|
||||
obj.trigger('a b');
|
||||
equal(obj.counter, 3);
|
||||
|
||||
obj.trigger('c');
|
||||
equal(obj.counter, 4);
|
||||
|
||||
obj.off({
|
||||
a: increment,
|
||||
c: increment
|
||||
}, obj);
|
||||
obj.trigger('a b c');
|
||||
equal(obj.counter, 5);
|
||||
});
|
||||
|
||||
|
||||
test("trigger all for each event", 3, function() {
|
||||
var a, b, obj = { counter: 0 };
|
||||
_.extend(obj, Backbone.Events);
|
||||
|
||||
Reference in New Issue
Block a user