我有以下数组来监视要由我正在处理的应用程序启动的小部件:
widgets = [{
selector: ".table",
init: function() {...}
},
{
selector: ".anothertable",
init: function() {...}
}]
每个初始化函数都在调用一个插件。插件完成任务后
它将选择器(例如“ .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
});