Permalink
Browse files

Add an evented mixin for Ember objects

In general, we should be using events more
extensively that happen to trigger callbacks as
a side effect.

This makes it possible for other objects to
register for notifications that would normally
be provided via callbacks, such as when a single
object manages a number of views.
  • Loading branch information...
wycats committed Feb 23, 2012
1 parent 5fe40a3 commit 2326580cda4383ee732e84a28407728fe4231bfb
@@ -13,3 +13,4 @@ require('ember-runtime/mixins/mutable_array');
require('ember-runtime/mixins/mutable_enumerable');
require('ember-runtime/mixins/observable');
require('ember-runtime/mixins/target_action_support');
require('ember-runtime/mixins/evented');
@@ -0,0 +1,25 @@
var get = Ember.get, set = Ember.set;

function xform(target, method, params) {
var args = [].slice.call(params, 2);

This comment has been minimized.

@krisselden

krisselden Feb 23, 2012

Member

Creating unnecessary garbage by creating an empty array to get at Array.prototype.slice.

Should just do slice = Array.prototype.slice at the top with get and set.

This comment has been minimized.

@wagenet

wagenet Feb 29, 2012

Member

@kselden Pull request?

method.apply(target, args);
}

Ember.Evented = Ember.Mixin.create({
bindEvent: function(name, target, method) {
if (!method) {
method = target;
target = null;
}

Ember.addListener(this, name, target, method, xform);
},

triggerEvent: function(name) {
Ember.sendEvent.apply(null, [this, name].concat([].slice.call(arguments, 1)));
},

unbindEvent: function(name, target, method) {
Ember.removeListener(this, name, target, method);
}
});
@@ -0,0 +1,51 @@
module("Object events");

test("a listener can be added to an object", function() {
var count = 0;
var F = function() { count++; };

var obj = Ember.Object.create(Ember.Evented);

obj.bindEvent('event!', F);
obj.triggerEvent('event!');

equal(count, 1, "the event was triggered");

obj.triggerEvent('event!');

equal(count, 2, "the event was triggered");
});

test("triggering an event can have arguments", function() {
var self, args;

var obj = Ember.Object.create(Ember.Evented);

obj.bindEvent('event!', function() {
args = [].slice.call(arguments);
self = this;
});

obj.triggerEvent('event!', "foo", "bar");

deepEqual(args, [ "foo", "bar" ]);
equal(self, obj);
});

test("binding an event can specify a different target", function() {
var self, args;

var obj = Ember.Object.create(Ember.Evented);
var target = {};

obj.bindEvent('event!', target, function() {
args = [].slice.call(arguments);
self = this;
});

obj.triggerEvent('event!', "foo", "bar");

deepEqual(args, [ "foo", "bar" ]);
equal(self, target);
});

0 comments on commit 2326580

Please sign in to comment.