jquery - javascript design pattern - callback though a public method -
i'd able use public method callback instead of passing argument
as in
function car() { var = this; this.ongearchanged = function(callback) { callback(); }; settimeout(that.ongearchanged, 2000); } var car = new car(); car.ongearchanged(function(){ console.log("gear changed"); });
instead of
var ongearchanged = function(){ console.log("gear changed") } var car = new car(arg, arg, ongearchange);
how go it? should follow observer pattern?
i think need this:
function event(sender) { this._sender = sender; this._listeners = []; } event.prototype = { attach: function (listener) { this._listeners.push(listener); }, notify: function (args) { (var = 0; < this._listeners.length; i++) { this._listeners[i](this._sender, args); } } };
you car
class:
function car(gear) { var self = this; self.gear = gear; self.gearchanged = new event(this); //example method trigger gearchanged event. in real code, may have different logic self.changegear = function (newgear){ self.gear = newgear; //notify subscribers self.gearchanged.notify(newgear); } }
example code subscribe events:
var car = new car("gear"); car.gearchanged.attach(function (sender,args){ console.log("gear changed"); console.log("new gear value is:" + args); }); //do logic may trigger gearchanged event. car.changegear("new gear");
you can attach more event handlers , these event handlers called. , can add more events like: tirechanged,.. structure.
Comments
Post a Comment