jQuery.when() 需要清除
jQuery.when() need to be cleared up
我有一个简单的.html页面,如下所示:
</html>
<head>
<script type="text/javascript" src="jquery/jquery-1.8.2.js"></script>
...
<script type="text/javascript">
var obj;
function document_load() {
obj = new mySpace.myClass();
console.log("end document load");
}
</script>
</head>
<body onload="document_load()">
...
...
</body>
</html>
myClass 是一个具有此构造函数的 TypeScript 类:
public constructor() {
console.log("begin constructor");
(<any>$).when(
jQuery.getJSON('path/myJson1.json', function (data) {
this.obj1 = data;
console.log("here1");
}),
jQuery.getJSON('path/myJson2.json', function (data) {
this.obj2 = data;
console.log("here2");
})
).then(function () {
if (this.obj1 && this.obj2) {
console.log("here3");
this.obj3 = new myClass3();
this.obj4 = new myClass4();
console.log("everything went ok");
}
});
}
实际上控制台打印了这个:
begin constructor
end document load
here1
here2
这种行为的原因(当然)是异步jQuery调用的原因(或者至少我猜是这样)。如何获得以下行为?
begin constructor
here1
here2
here3
everything went ok
end document load
我澄清了 json 是正确的(我试图打印它们并且它们是正确的)。
这是因为您没有向jQuery.when返回承诺,因此调用回调并且this.obj1 && this.obj2
都是null。
更好的方法是:
(<any>$).when(
jQuery.getJSON('path/myJson1.json'),
jQuery.getJSON('path/myJson2.json')
)
.then(function (obj1, obj2) {
// Code
});
将所有函数替换为箭头函数 (=>)。这将确保"this"指向所有函数体中的正确事物。
更多 : https://www.youtube.com/watch?v=tvocUcbCupA
相关文章:
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 单击jquery清除输入值
- 如何在Microsoft VirtualEarth 6.3中使用纯javascript清除整个形状层
- 清除以前的$_GET值或不获取仅隐藏字段的值
- jQuery.when()在循环中被忽略
- Javascript清除缓存以清除基本身份验证凭据
- 清除启动日期选取器值
- 在 SlickGrid 中编辑后,根据不同列中的另一个单元格清除单元格
- php页面,该页面在清除值后接受输入
- 清除数据并将旧值附加到文本框中
- 使用javascript清除Asp.NET FreeTextBox(RTF文本框)
- 如何使Visual Studio自动清除Javascript控制台
- 使用javascript或html本身清除文本字段
- 清除函数中if语句内部不起作用的间隔
- 我应该/如何清除mousemove JQuery事件侦听器
- 为什么$.when().pipe().then()有效,而$.when
- 为什么有些jQuery程序员使用像$.get、$.getJSON和$.when这样的jQuery函数来代替$.ajax
- 从定位目标中的元素中清除类
- 使用查询字符串方法清除浏览器缓存
- jQuery.when() 需要清除