Last active
December 25, 2015 13:58
-
-
Save Saneyan/6987168 to your computer and use it in GitHub Desktop.
Binding functions.
This file contains hidden or 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
| var Binder = exports.Binder = function () { | |
| this._funcs = []; | |
| }; | |
| Binder.prototype.bind = function (func) { | |
| var args = Array.prototype.slice.call(arguments, 1), | |
| trg = this._trigger; | |
| this._funcs.unshift(function (next) { | |
| func.apply(func.prototype.constructor, args.concat([next])); | |
| }); | |
| return this; | |
| }; | |
| Binder.prototype.trigger = function (num) { | |
| var len = num === undefined ? this._funcs.length - 1 : num >= 0 ? num : -1; | |
| len >= 0 && this._funcs[len](this.trigger.bind(this, len - 1)); | |
| }; |
This file contains hidden or 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
| var binder = new require('./binder').Binder; | |
| binder.bind(f1, 'm1') | |
| .bind(f2, 'm2') | |
| .bind(f3, 'm3') | |
| .trigger(); | |
| // As a result: | |
| // f1: m1 | |
| // f2: m2 | |
| // f3: m3 | |
| function f1(m) { log('f1: ' + m); } | |
| function f2(m) { log('f2: ' + m); } | |
| function f3(m) { log('f3: ' + m); } | |
| function log(m) { console.log(m); } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment