2

我有一个这样的命名空间设置:

var myApp = {};
(function(context) {
    var id = 0;

    context.next = function() {
        return id++;
    };

    context.reset = function() {
        id = 0;
    }
})(myApp);
window.console && console.log(
    myApp.next(),
    myApp.next(),
    myApp.reset(),
    myApp.next()
) //0, 1, undefined, 0

我现在想从 myApp 获得一个回调,我可以在命名空间之外捕获它。

任何想法如何使用我的命名空间设置进行设置?

例如这样的:

myApp.setCallback('next', function() {
    alert('hello');
 });
4

2 回答 2

3

您可以测试回调是否存在,如果存在则运行该函数:

var myApp = {};

(function(context) {
    var id = 0;

    context.next = function() {
        return id++;
    };

    context.reset = function() {
        id = 0;

        if(typeof this.onreset === 'function') {
            this.onreset();
        }
    }
})(myApp);


myApp.onreset = function() {};
于 2013-05-11T12:20:27.297 回答
1

您需要添加一个包含回调函数的对象和一个注册它们的函数:

var myApp = {};
(function(context) {
    var id = 0;

    var callbacks = {};

    context.next = function() {
        id++;
        doCallbacks('next');
        return id;
    };

    context.setCallback = function(event, f) {
        if(!callbacks[event] || !callbacks[event] instanceof Array) {
            callbacks[event] = [];
        }
        callbacks[event].push(f);
    }

    context.reset = function() {
        id = 0;
    }

    function doCallbacks(key /*, event */) {
        if(callbacks[key] && callbacks[key] instanceof Array) {
            for(var i=0; i < callbacks[key].length; i++) {
                callbacks[key][i](/*event*/);
            }
        }
    }
})(myApp);

然后你可以打电话:

myApp.setCallback('next', function() {
    alert('hello');
});

工作的jsFiddle

使用事件对象工作 jsFiddle

您可能需要稍微调整对数组的检查,但我不知道如何完美地做到这一点。

于 2013-05-11T12:26:52.037 回答