gpt4 book ai didi

javascript 设计模式 - 通过公共(public)方法回调

转载 作者:行者123 更新时间:2023-12-02 18:29:30 27 4
gpt4 key购买 nike

我希望能够使用公共(public)方法进行回调,而不是将其作为参数传递

 function Car() {

var that = this;

this.onGearChanged = function(callback) {

callback();
};

setTimeout(that.onGearChanged, 2000);
}

var car = new Car();
car.onGearChanged(function(){
console.log("gear changed");

});

而不是

var onGearChanged = function(){
console.log("gear changed")
}
var car = new Car(arg, arg, onGearChange);

我该怎么办?我应该遵循观察者模式吗?

最佳答案

我认为你需要这样的东西:

function Event(sender) {
this._sender = sender;
this._listeners = [];
}

Event.prototype = {
attach: function (listener) {
this._listeners.push(listener);
},
notify: function (args) {
for (var i = 0; i < this._listeners.length; i++) {
this._listeners[i](this._sender, args);
}
}
};

您的汽车类(class):

function Car(gear) {
var self = this;

self.Gear = gear;
self.GearChanged = new Event(this);

//Example method to trigger your GearChanged event. In your real code, you may have different logic
self.changeGear = function (newGear){
self.Gear = newGear;
//notify all subscribers
self.GearChanged.notify(newGear);
}
}

订阅事件的示例代码:

var car = new Car("gear");
car.GearChanged.attach(function (sender,args){
console.log("gear changed");
console.log("new gear value is:" + args);
});
//do some logic that may trigger gearChanged event.
car.changeGear("new Gear");

您可以附加更多事件处理程序,所有这些事件处理程序都将被调用。您还可以使用此结构轻松添加更多事件,例如:tireChanged,..。

关于javascript 设计模式 - 通过公共(public)方法回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17973070/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com