while vs setInterval



我有以下数组来监控我正在开发的应用程序启动的小部件:

widgets = [{
 selector: ".table",
 init: function() {...}
},
{
 selector: ".anothertable",
 init: function() {...}
}]

每个init函数都在调用一个插件。插件完成任务时它将选择器(例如".table")推送到另一个名为"readyWidgets"的数组

现在的问题是:

一旦所有选择器嵌套在主窗口小部件数组下,我该如何判断是否存在于readyWidgets数组中?

我有点停电了,虽然我有一个解决方案,但我想我缺少一个更好的解决方案。

这就是我想到的:

init: function() {
    // this will hold each widget selector
    // and look for it later in readyWidgets array
    var widgetsPending = []
    // initialize each widget in widgets array
    // (only if the selector matches at least one element)
    this.widgets.forEach(function(widget) {
        $(widget.selector).length && widgetsPending.push(widget.selector) && widget.init()
    }, this)
    // use setInterval to check if all values in widgetsPending array
    // are present within this.readyWidgets
    var that = this
    var interval = setInterval(function() {
        // temporary just to make sure the interval is cleared
        console.log(that.readyWidgets)
        // if a value in widgetsPending is not found in 
        // that.readyWidgets, pageReady will be marked false
        var pageReady = true
        widgetsPending.forEach(function(selector) {
            if (that.readyWidgets.indexOf(selector) == -1) {
                pageReady = false
            }
        })
        // if widgetsReady is true, clear the interval
        pageReady && clearInterval(interval)
    }, 300)     
}

如果你对如何改进有任何建议,请告诉:)

类似这样的东西:

var loadOperations = [];
objects.forEach(function (obj) {
    var loadComplete = $.Deferred();
    loadOperations.push(loadComplete);
    // long running async function call. this function can return deferred or promise as well
    obj.someLongRunningEGLoadOperation(function() { // async function complete callback
        loadComplete.resolve();
    });
});
$.when.apply($, loadOperations).done(function () {
    // do something then all long running operations are completed
});

最新更新