我以一种非常通用的方式在 JS 中实现了观察者模式。现在我意识到有一个概念问题,我不知道如何解决它。你能给我一个提示如何解决它吗?(特别是以一种非常聪明的方式:-))这是代码:
var Oberserverable = function() {
var subscribers = { /* some delegated functions in here */ };
return {
attach: function (obj, fn) { subscribers[obj] = { src: obj, fn: fn }; },
detach: function (obj) { delete subscribers[obj]; },
notify: function (args) {
for(var o in subscribers) {
if(typeof args === "object") { args.target = subscribers[o].src; }
/* TODO return */ subscribers[o].fn.call(window, args);
}
},
count: function () { var size = 0; for(var o in subscribers) { size++; } return size; }
};
};
我希望每个委托函数都返回它的值。但这将结束我想要预防的循环。
我使用它的示例;糟糕的 IE8 事件处理的解决方法:
window.addEvent = function (obj, type, fn, bub) {
if(obj.addEventListener) {
return obj.addEventListener(type, fn, bub ? bub : false);
}
if(obj.attachEvent && type == "DOMContentLoaded") type = "load";
// no use of attachEvent() 'cause of very buggy behaviour in IE<=8
// http://stackoverflow.com/questions/15952943/ie-attachevent-call-returns-true-but-handler-shows-null
if(!obj["e"+type]) obj["e"+type] = new Oberserverable();
obj["e"+type].attach("e"+obj+fn, fn);
if(!obj["on"+type]) {
obj["on"+type] = function(e) {
e = e || window.event;
e.cancelBubble = bub;
return obj["e"+type].notify(e) || (type != "contextmenu"); // suppressing context menu in IE8 as default
};
}
}