javascript - javascript回调函数的泛化

标签 javascript windows-8 callback

我想创建大约 10 个 XML HTTP 请求,如下所示。我想将 i 的值用于第一个“子级”引用,但是随着 i 在执行回调之前发生变化,i 的值code> 与“结果”选项卡中的 url 不匹配。我如何概括这一点?

var i = 1;
WinJS.xhr({
    url: root.results[i].profile_image_url_https,
    responseType: 'blob'
}).done(function (result) {
    var imgTag = theDiv.children[1].children[0];
    var imageBlob = URL.createObjectURL(result.response, {
        oneTimeOnly: true
    });
    imgTag.src = imageBlob; //tempLocalUrl;
});

i = 2;

WinJS.xhr({
    url: root.results[i].profile_image_url_https,
    responseType: 'blob'
}).done(function (result) {
    var imgTag = theDiv.children[2].children[0];
    var imageBlob = URL.createObjectURL(result.response, {
        oneTimeOnly: true
    });
    imgTag.src = imageBlob; //tempLocalUrl;
});

最佳答案

典型的方法是使用一个额外的函数(立即执行)来捕获循环变量的当前值,例如:

var i = 1;

WinJS.xhr({
    url: root.results[i].profile_image_url_https,
    responseType: 'blob'
}).done(function (inner_i) {
  // return the actual callback
  return function (result) {
    // use `inner_i` as needed
    var imgTag = theDiv.children[1].children[0];
    var imageBlob = URL.createObjectURL(result.response, {
      oneTimeOnly: true
    });
    imgTag.src = imageBlob; //tempLocalUrl;
  };
}(i)); // <= pass outer `i`

关于javascript - javascript回调函数的泛化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13643047/

相关文章:

Javascript:在嵌套函数中返回 promise

javascript - 使用 CSS/Javascript 将动态文本包裹在旋转圆柱体周围 (splitting.js)

sql - 部署使用 SQLite 的 Windows 8 Metro 应用程序

Java 错误 : incorrect time in MSK

C#/C++ 回调作为 NULL 传递

javascript - AJAX 调用完成后如何执行操作?

Javascript定义的对象检查

javascript - jQuery UI 对话框 - 在已打开的 jQuery UI 对话框中保留单击的链接

javascript - 为什么这个闭包还需要在外部函数处返回?

javascript - 从方法中查询 Windows 8 应用程序中的 DOM