我正在使用 move.js
制作动画游戏,但它需要很长时间,因此当玩家单击正确的解决方案时,它会在正确的解决方案更改其颜色之前显示获胜消息,所以我使用延迟对象来触发事件并在动画结束时捕获它。
这是我的代码:
var deferred = new $.Deferred();
click(e);
//show message when game is over
$.when(deferred).then(function(){
if (this.checkIfWin()){
alert('you won !');
this.nextLevel();
}
});
function click(e){
move(e)
.set('background-color','black')
.delay('0.1s')
.end();
deferred.notify();
}
但没有收到通知,消息也没有显示。我在这里错过了什么?
最佳答案
因为 JavaScript 中的动画是异步的(它们通过计时器运行),所以知道动画何时完成的唯一方法是 Hook 某种完成回调或完成通知。
我自己并不了解 move.js,但看起来您可以通过向 .end(fn)
方法提供回调来获得这样的回调。但是,您还必须修复代码,因为 this.checkIfWin()
中的 this
在这两个代码块中都不是正确的值。我不知道你想要它是什么(因为你没有显示代码的那部分),但你必须引用除 this
之外的其他对象。无论如何,这里是使用和不使用延迟的代码的一般结构。
var deferred = new $.Deferred();
// your code was using this here
// so I will save a reference to it that can be used later, but there is
// probably a better way to do this if I could see the rest of your code
var obj = this;
click(e);
//show message when game is over
deferred.promise().then(function(){
if (obj.checkIfWin()){
alert('you won !');
obj.nextLevel();
}
});
function click(e){
move(e)
.set('background-color','black')
.delay('0.1s')
.end(function() {
deferred.resolve();
});
}
<小时/>
在这种情况下,您似乎并不真正需要使用延迟,因为您可以将完成代码放在回调中:
// your code was using this here
// so I will save a reference to it that can be used later, but there is
// probably a better way to do this if I could see the rest of your code
var obj = this;
click(e);
function click(e){
move(e)
.set('background-color','black')
.delay('0.1s')
.end(function() {
if (obj.checkIfWin()){
alert('you won !');
obj.nextLevel();
}
});
}
关于javascript - 异步任务完成后通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24971676/