Skip to content

Instantly share code, notes, and snippets.

@AutoSponge
Last active October 13, 2015 23:58
Show Gist options
  • Save AutoSponge/4276678 to your computer and use it in GitHub Desktop.
Save AutoSponge/4276678 to your computer and use it in GitHub Desktop.
Observable AOP
function observable(fn, topic) {
function observed() {
var result;
PubSub.publish(topic + "/before", {obj: this, args: arguments});
result = fn.apply(this, arguments);
PubSub.publish(topic + "/after", {obj: this, args: arguments, result: result});
return result;
};
observed.before = function (fn) {
PubSub.subscribe(topic + "/before", fn);
return this;
};
observed.after = function (fn) {
PubSub.subscribe(topic + "/after", fn);
return this;
};
return observed;
}
var obj = {
add: function () {
this.num += Array.prototype.reduce.call(arguments, function (a, b) {
return a + b;
});
return this.num;
},
num: 1
};
obj.add = observable(obj.add, "obj/add");
obj.add.before(function (data, topic) {
console.log("adding " + Array.apply(null, data.args) + " to num.");
this.start = this.num;
})
.after(function (data, topic) {
console.log("num is now " + data.result);
this.end = this.num;
});
obj.add(1,2,3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment