From c0a3a9439e54d7c305377a4ec07911b0c7cd57da Mon Sep 17 00:00:00 2001 From: Andrew Stewart Date: Thu, 19 Mar 2015 10:42:51 -0700 Subject: [PATCH] Add #respond method to work with events/callbacks --- lib/basestar.js | 17 +++++++++++++++++ spec/lib/adaptor.spec.js | 6 +++++- spec/lib/basestar.spec.js | 28 +++++++++++++++++++++++++++- 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/lib/basestar.js b/lib/basestar.js index 7e05292..ff49806 100644 --- a/lib/basestar.js +++ b/lib/basestar.js @@ -33,6 +33,23 @@ Utils.subclass(Basestar, EventEmitter); // Returns the klass where the methods have been proxied Basestar.prototype.proxyMethods = Utils.proxyFunctionsToObject; +// Public: Triggers a callback and emits an event with provided data +// +// event - name of event to be triggered +// callback - callback function to be triggered +// ...data - additional arguments to be passed to both event/callback +// +// Returns nothing +Basestar.prototype.respond = function(event, callback) { + var args = Array.prototype.slice.call(arguments, 2); + + this.emit.apply(this, [event].concat(args)); + + if (typeof callback === "function") { + callback.apply(this, args); + } +}; + // Public: Defines an event handler that proxies events from a source object // to a target object // diff --git a/spec/lib/adaptor.spec.js b/spec/lib/adaptor.spec.js index 0aeff11..3498f7c 100644 --- a/spec/lib/adaptor.spec.js +++ b/spec/lib/adaptor.spec.js @@ -4,7 +4,11 @@ var Adaptor = source("adaptor"); describe("Adaptor", function() { - var adaptor = new Adaptor({ name: "adaptor" }); + var adaptor; + + beforeEach(function() { + adaptor = new Adaptor({ name: "adaptor" }); + }); describe("#constructor", function() { it("sets @name to the provided name", function() { diff --git a/spec/lib/basestar.spec.js b/spec/lib/basestar.spec.js index 1877da0..769df22 100644 --- a/spec/lib/basestar.spec.js +++ b/spec/lib/basestar.spec.js @@ -50,8 +50,34 @@ describe("Basestar", function() { }); }); - describe("#defineEvent", function() { + describe("#respond", function() { + var listener, callback, child; + var Child = function Child() {}; + + Utils.subclass(Child, Basestar); + + beforeEach(function() { + child = new Child(); + + listener = spy(); + callback = spy(); + + child.on("event", listener); + + child.respond("event", callback, "arg1", 2, { three: true }); + }); + + it("triggers the callback with all additional arguments", function() { + expect(callback).to.be.calledWith("arg1", 2, { three: true }); + }); + + it("emits an event with all additional arguments", function() { + expect(listener).to.be.calledWith("arg1", 2, { three: true }); + }); + }); + + describe("#defineEvent", function() { var ProxyClass = function ProxyClass() {}; var EmitterClass = function EmitterClass(update) {