在for循环中返回functioncalls的值

时间:2013-09-09 08:17:45

标签: javascript

我以非常通用的方式在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 Eventhandeling的解决方法:

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
        };
    }
}

1 个答案:

答案 0 :(得分:0)

EUREKA!

我想我已经有了解决方案。实际问题不是Oberserverable模式,而是示例案例本身。也许我应该做某事。像这样:

        obj["on"+type] = function(e) {
            e = e || window.event;  
            e.cancelBubble = bub;
            obj["e"+type].notify(e); 
            if(typeof e.preventDefault == "function") {
                return e.preventDefault();
            }
        };

另一部分与此类似:

addEvent(document, "contextmenu", function(e) {
    document.defaultAction = false;
    if (e.preventDefault)
        e.preventDefault();
    else
        e.preventDefault = function() { return false; };

    if (e.stopPropagation)
        e.stopPropagation();

    if (e.returnValue)
        e.returnValue = false;
});

它似乎以这种方式工作,但我不确定合规性和副作用。