【发布时间】:2011-02-22 11:46:24
【问题描述】:
我有一个名为 TweenManager 的 Javascript 对象,其中包含一个 Tween 对象数组。 TweenManager 应该在 'tween' 数组中的每个 tween 上调用 step() 方法,并且所有的 tween 应该同时运行。
但是,实际发生的情况是 TweenManager 一次只运行一个补间,并且在前一个补间完成之前不会启动下一个。
这是补间管理器的代码
更新:look at it here 可能更有意义
//Manage all tweens
function TweenManager(){
this.tweens = new Array();
this.timer;
this.start = function(){
this.timer = setInterval(this.run, 1, this);
}
// Loop through all tweens and call the step method
this.run = function(myself){
console.log(myself.tweens.length);
// stop the interval if the tween array is empty
if(myself.tweens.length == 0){
clearInterval(myself.timer)
}
// loop through all tweens and call the step() method
// !! Here's there the problem appears to be
for(i = 0; i < myself.tweens.length; i++){
thisTween = myself.tweens[i]
console.log(thisTween.element.attr('id'));
thisTween.step() // if I remove this, the line above logs the id's as expected
// clean up if the tween is complete
if(thisTween.t == thisTween.d){
myself.tweens.splice(i, 1);
}
}
}
this.addTween = function(b,c,d,element,suffix, decimal){
this.tweens.push( new Tween(b,c,d,element,suffix, decimal) )
}
}
问题似乎出在 for 循环中。我有一种预感,这可能与在setInterval 中传递this 有关,虽然这只是一种预感,但我不明白问题可能是什么。我对变量范围和诸如此类的东西感到困惑。
这是补间对象(是的,从罗伯特彭纳那里抄袭)
// Tween a number, add a suffix and insert it into an element
function Tween(b, c, d, element, suffix, decimal){
this.t = 0;
this.c = c;
this.d = d;
this.b = b;
this.element = element;
this.suffix = suffix;
this.step = function(){
if(this.t != this.d){
this.t += 1
var flip = 1
if (this.c < 0) {
flip *= -1
this.c *= -1
}
i = flip * (-Math.exp(-Math.log(this.c)/this.d * (this.t-this.d)) + this.c + 1) + this.b
if(!decimal){
this.element.html(Math.round(i) + this.suffix)
}else{
output = (Math.round(i * 10) / 10 + this.suffix)
formattedOutput = ( output - Math.round(output) == 0 ) ? output + ".0" : output;
this.element.html(formattedOutput)
}
}
}
}
这是实现
tweenManager = new TweenManager();
tweenManager.addTween(0,80,300, $("#el1"), "°", false)
tweenManager.addTween(0,60,400, $("#el2"), "’", false)
tweenManager.addTween(0,12.5,300, $("#el3"), "", true)
tweenManager.start()
与往常一样,我们非常感谢任何帮助、提示或推动正确方向。
【问题讨论】:
标签: javascript oop for-loop