2012-03-02 171 views
0

我想在JavaScript中创建一个具有动画运行的对象,当它完成时调用另一个方法。Javascript对象访问它的属性

function panel_manager() { 
    this.animating = false; 

    this.doAnimate = function (nPanel) { 
     //if we're still moving panels, do nothing 
     if(this.animating) return; 

     this.animating = true; 

     //enlarge new panel 
     $("#panel" + this.focusedPanel).animate({width:"115px"},1000, this.endAnim); 
    } 

    this.endAnim = function() { alert("called"); this.animating = false; } 
} 

一大堆已经削减了简洁和这个代码的工作时,它是不是一个对象中,并使用全局变量。警报运行,但动画不会改变。

+0

'$( “#面板” + this.focusedPanel).animate(等等,1000,this.endAnim);'< - 'this.endAnim'指的是'$( “#面板” + this.focusedPanel)'。 – 2012-03-02 01:10:42

回答

2

变量。

function panel_manager() { 
    var that = this; 
    this.animating = false; 
    this.doAnimate = function (nPanel) { 
     if(this.animating) return; 
     this.animating = true; 
     $("#panel" + this.focusedPanel).animate({width:"115px"},1000, that.endAnim); 
    } 
    this.endAnim = function() { alert("called"); that.animating = false; } 
} 
+0

工程,我认为这是较少的开销/处理来做到这一点。 – BeaverusIV 2012-03-02 01:44:43

+0

我会指出有更多优化机会(主要缓存面板对象),但我希望OP能够看到实现预期结果所需的细微差异。代理(或者Function.prototype.bind)在一个函数将被共享的时候被更多地使用 - 这个函数只属于单个实例,所以对闭包的一个变量进行范围化是简单的。 – AutoSponge 2012-03-02 02:52:45

-1

this.doAnimate里面添加一个$ .proxy。

var callback = $.proxy(this.endAnim, this); 

$("#panel" + this.focusedPanel).animate({width:"115px"},1000, callback); 

基本上,问题是,当你把它分配给这样的回调你失去了你this值。代理将确保使用正确的this调用该函数。

干杯!

+0

我认为这是我的问题,只是找不到任何解决方案。谢谢,它现在有效。 – BeaverusIV 2012-03-02 01:15:08

+0

你在关闭中,当你只能使用一个变量时,不要使用$ .proxy。 – AutoSponge 2012-03-02 01:18:24

+0

请详细说明,AutoSponge。谢谢。 – BeaverusIV 2012-03-02 01:19:09