【问题标题】:Why is callback undefined?为什么回调未定义?
【发布时间】:2013-11-01 16:49:40
【问题描述】:

您好,我使用对象构造函数来管理一些动画,在某些情况下,我想在动画完成时传递一个回调以使其他一些元素出现。问题是如果在 if 语句中我记录了一种回调类型,它是一个有效的函数,但是当我在 if 语句中执行日志时,如果总是未定义,我很感激有人可以帮助我,我也离开了代码,所以你们可以检查一下。

// CONSTRUCTOR WHO MANAGE THE ANIMATIONS FOR THE WEBSITE

function SpriteAnimation(frameWidth, spriteWidth, spriteElement, shouldLoop, frameRate){
    this.frameWidth = frameWidth;
    this.spriteWidth = spriteWidth;
    this.selector = document.getElementById(spriteElement);
    this.shouldLoop = shouldLoop ;
    this.curPx = 0;
    this.frameRate = frameRate;
}

SpriteAnimation.prototype.start = function(callback){
    this.selector.style.backgroundPosition = "-" + this.curPx + "px 0px";
    this.curPx += this.frameWidth;

    if (this.curPx < (this.spriteWidth - this.frameWidth)){
        setTimeout(this.start.bind(this), this.frameRate);
    }else if (this.curPx > (this.spriteWidth - this.frameWidth)){
        console.log(typeof callback);
    }else if(this.shouldLoop){
        this.curPx = 0;
        this.start();
    }
};

稍后在代码中我实例化它并运行开始:

var letter = new SpriteAnimation(790, 18163, "letter", false, 53.3);

letter.start(function(){
    console.log("hola");
});

【问题讨论】:

    标签: javascript jquery oop constructor callback


    【解决方案1】:

    您没有在setTimeout 中传递回调,我建议您这样做:

        setTimeout(function(){
            this.start(callback);
        }, this.frameRate);
    

    【讨论】:

      【解决方案2】:

      一种可能是 setTimeout 调用了 start 函数

      SpriteAnimation.prototype.start = function(callback){
          this.selector.style.backgroundPosition = "-" + this.curPx + "px 0px";
          this.curPx += this.frameWidth;
      
          if (this.curPx < (this.spriteWidth - this.frameWidth)){
              setTimeout((function(){
                  this.start(callback)
              }).bind(this), this.frameRate);
          }else if (this.curPx > (this.spriteWidth - this.frameWidth)){
              console.log(typeof callback);
          }else if(this.shouldLoop){
              this.curPx = 0;
              this.start();
          }
      };
      

      【讨论】:

      • 我想知道为什么在 de setTimeout 里面你把函数包装在 () 里面...这个答案对我来说效果很好,只是想了解事情的原因
      • @JhonnatanGonzalezRodriguez 因为我想在setTimeout 处理程序上调用bind(this)...所以只需将其包裹在() 中。但由于旧的浏览器兼容性问题,我建议使用$.proxy() 而不是.bind()
      • 使用$.proxy()setTimeout($.proxy(function () { this.start(callback); }, this), this.frameRate);
      • the () 使该功能成为自动弹出功能?...对不起,英语不是我的母语
      • mm 不知道你可以在 java 脚本中包装这样的东西,你有资源我可以阅读一下吗?...也感谢你的帮助和耐心跨度>
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 2021-12-11
      • 2019-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多