Last active
October 13, 2015 23:58
-
-
Save AutoSponge/4276678 to your computer and use it in GitHub Desktop.
Observable AOP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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