2010-11-08 102 views
1

这是推动我坚果 - 我一直团团团团转,这没有喜悦。我加载了多个动态图像,并且有一个简单的Javascript对象,我为每个图像实例化,并且具有一个回调来在异步加载图像时呈现图像。的Javascript Image.onload回调目标函数

我已经验证回调代码在独立基础上工作得很好(即,我可以在图像加载后手动调用回调,并且图像正确呈现),并且我已验证图像本身已成功加载(通过将对象的回调切换为简单的一行日志记录功能),但是当我试图将它们结合在一起时,回调显然永远不会被调用。

我是比较新的JS,我怀疑,我失去了一些东西有关定义对象中的单向函数的基础,但尽管有很多的谷歌搜索的,可以不知道是什么。

请能有人告诉我我的方式错误?

function ImageHolder(aX,aY,aW,aH, anImageURL) { 
    this.posx=aX; 
    this.posy=aY; 
    this.posw=aW; 
    this.posh=aH; 
    this.url=anImageURL; 

    this.myImage = new Image(); 
    this.myImage.onload=this.onload; 
    this.myImage.src=anImageURL; 
    this.onload=function() { 

     try { 
      var d=document.getElementById("d"); 
      var mycanvas=d.getContext('2d'); 
      mycanvas.drawImage(this.myImage, this.posx, this.posy, this.posw, this.posh); 
      } catch(err) { 
       console.log('Onload: could not draw image '+this.url); 
       console.log(err); 
      } 
    }; 
} 

回答

7

您有两个问题:第一,this.onload没有定义在您将它分配给图像的位置。您可以通过错过了存储onload处理功能的this属性的阶段,解决这个问题。第二个问题是,当onload处理函数被调用,this未设置为你认为它是(其实,这是对刚刚加载的Image对象的引用)。你需要存储到当前ImageHolder对象的引用和事件处理函数中使用它,而不是this

新代码:

var that = this; 

this.myImage = new Image(); 
this.myImage.onload=function() { 
    try { 
     var d=document.getElementById("d"); 
     var mycanvas=d.getContext('2d'); 
     mycanvas.drawImage(that.myImage, that.posx, that.posy, that.posw, that.posh); 
    } catch(err) { 
     console.log('Onload: could not draw image '+that.url); 
     console.log(err); 
    } 
}; 
this.myImage.src = anImageURL; 
+0

谢谢你,谢谢你,谢谢你。现在你指出'这个'参考,这一切都非常有意义。 – Laura 2010-11-08 14:13:46