从另一个数组中获取具有相同项目的项目的最佳做法是什么

时间:2011-08-24 09:36:08

标签: javascript loops

好的,我知道这个标题很复杂,但问题很难在一行中做出来......抱歉。

目标:我希望在所有模块都可用时运行回调 问题:最快的方法是什么? 例如:

问题从“runCallbacks”函数开始,该函数获取所有新添加的对象,如下所示:

runCallbacks(newItems/*as array ['a','b','c'];*/){
    // now I would need to understand the dependencies of the callbacks
    // each callback might depend on one or more objects
    // iNeed(['a','b'], toRunThis);
    //           |          |-callback to run when those are ready
    //           |-are the dependencies

我在想的是:

 callbacks = [[[callbackFunction],['loadedItems'],['notLoadedItems']]]
              |-----------it's a single callback--------------------|

表现不错还是你有更好的想法? 谢谢

另一个例子

this.use(['a', 'b'], function(){/* do something with 'a' and 'b' only when are ready */})
use: function(paths, callback, target/*not used in this case*/){
    // "a", "b", 'c' module is available
    // "d", 'e' module is not available
    this.callbacks.push([[target], ['a', 'b', 'c'], ['d', 'e']]);
    //                               |      |-not loaded
    //                               |-loaded
}

// then an object might be added
this.add({...})

// then will check if this new object may make some callbacks to run
function(newPaths/* ['d'] */){
    // loop all callbacks items
    // remove items from [not loaded array] and put to [loaded array] if
    // exists in newPaths
    // in this case the callback already has: a,b,c; but misses: d,e;
    // now it will add "d" to the loaded array
    // and now only miss the "e" path

因此,如果回调需要“a”和“b”但不存在,则会在两者都准备就绪时保存回调 我添加“a”和“b”模块,然后我想知道女巫回调已准备好运行;

回调可能有多重依赖 “a”模块可能被多个回调使用 这就是为什么有点复杂

1 个答案:

答案 0 :(得分:1)

如果你正在运行jquery,请查看$ .when,否则会有像promises.js这样的库(在这里展开:http://blogs.msdn.com/b/rbuckton/archive/2010/01/29/promises-and-futures-in-javascript.aspx)。这个想法就是当依赖准备就绪并得到解决时,承诺就会触发事件。