订阅者模式中此的Javascript范围
我已经看到了解决这个问题的方法,但似乎再也找不到了订阅者模式中此的Javascript范围,javascript,design-patterns,Javascript,Design Patterns,我已经看到了解决这个问题的方法,但似乎再也找不到了 // // A simple implementation of the subscriber pattern // var Subject = function() { this._observers = []; }; // Here lies the problem Subject.prototype.attach = function(observer, func) { this._observers.push(ob
//
// A simple implementation of the subscriber pattern
//
var Subject = function()
{
this._observers = [];
};
// Here lies the problem
Subject.prototype.attach = function(observer, func)
{
this._observers.push(observer);
this._observers.push(func);
};
// And this only makes the problem worse
Subject.prototype.notify = function(pData)
{
var len = this._observers.length;
for(var i = 0; i < len; i += 2)
this._observers[i][this._observers[i + 1]](pData, this._observers[i]);
};
// Store the data related to the generic Observer
var Observer = function(pId){
this._el = pId;
};
//
// Notify and Update represent two possible functions that do different stuff
//
Observer.prototype.notify = function(pData, pThis)
{
document.getElementById(pThis._el).textContent = 'Notify: ' + pData;
};
Observer.prototype.update = function(pData, pThis)
{
document.getElementById(pThis._el).textContent = 'Update: ' + pData;
};
// In action
var server = new Subject();
var client1 = new Observer('observer_1' /* the ID to some DOM element */);
var client2 = new Observer('observer_2');
// Another manifestation of the problem I've ran into
server.attach(client1, 'notify');
server.attach(client2, 'update');
server.notify('[some data]');
被称为,因为它是从主体内部被称为
this._el
指的是主语。\u el,它不存在。我的解决方法是在我的主题中注册两件事:一个对观察者的引用,以及一个包含该观察者内回调名称的字符串。然后,当主体广播通知时,它调用已注册的回调,并将对观察者的引用发送给观察者,该引用将用作:
// instead of this._el (which would refers to server._el,
// do <observer_1>._el
//而不是这个。_el(指服务器。_el,
//你知道吗
我希望我已经清楚地表达了我的问题,这样我可以得到我需要的帮助
谢谢!
其要点是作用域。设置回调函数时,必须确保它在观察者的上下文中执行:
// Here lies the problem
Subject.prototype.attach = function(observer, func)
{
this._observers.push(observer);
this._observers.push(_.bind(func, observer));
};
最简单的方法是使用下划线.js并更改绑定。您还可以使用call()和apply()创建自己的绑定
这可能更接近您想要的:
// Here lies the problem
Subject.prototype.attach = function(observer, func)
{
this._observers.push(observer);
this._observers.push(_.bind(func, observer));
};