4

如何从 dojo 要求块中返回值?假设我有这样的设置:

<div class = "people">
    <span class = "name"> Joe Bloggs </span> the Baker <br />
    <span class = "name"> John Smith </span> the Chef <br />
</div>


function getNames () {
    require(["dojo/query", "dojo/domReady!"], function(query) {

        var names = [];
        query (".name").forEach (function (node) {
            names.push (node.innerHTML);
        });

        return names;
    });
}

function doSomethingWithNames () {

    var names = getNames (); // names is always undefined

}

我知道它为什么会发生 - require 块是异步执行的,因此在 getNames 返回之前分配了 doSomethingWithNames 中的变量名。但是我该如何解决呢?

4

1 回答 1

4

添加自定义回调:

function getNames (callback) {
    require(["dojo/query", "dojo/domReady!"], function(query) {

        var names = [];
        query (".name").forEach (function (node) {
            names.push (node.innerHTML);
        });

        callback(names);
    });
}

function doSomethingWithNames () {

    getNames (function(names) {
        //do your stuff with the return here
        //names will now be populated
    });

}
于 2013-08-23T13:34:21.957 回答