我正在尝试创建一个包含函数的dojo类,这些函数又调用此类中的其他函数,如下所示:
dojo.provide("my.drawing");
dojo.declare("my.drawing", null, {
constructor: function(/* Object */args){
dojo.safeMixin(this, args);
this.container = args[0];
},
addPoint: function(event){
//calculate the x and y values by offsetting correctly
var pos = dojo.coords(container);
var x = event.clientX - pos.x;
var y = event.clientY - pos.y;
this.addAbsPoint(x,y);
},
addAbsPoint: function(x,y){
//do something here with the absolute x and y values
}
});
上面(修剪过的)代码是在dojo.gfx表面上添加一个点.当我尝试运行它时,我收到以下控制台错误:
Uncaught TypeError: Object #<an HTMLDivElement> has no method 'addAbsPoint'
函数addPoint(event)被正确调用,但它在同一对象中引用函数addAbsPoint(x,y)时失败.道场有可能吗?我怎么能完成它?
解决方法:
addPoint()未正确调用,不在正确的上下文中.从它的签名判断我的心灵能力告诉我你用它作为事件处理程序,但你没有正确地做到这一点.
你这样做:
var myDrawing = new my.drawing(someArgs);
// this is incorrect:
dojo.connect(someDomNode, "onclick", myDrawing.addPoint);
// or, less incorrect, yet incorrect too:
surface.connect("onclick", myDrawing.addPoint);
在JavaScript中,上面的行传递一个函数,而不是你想象的绑定方法.您需要传递一个上下文(一个对象来调用函数):
// the node connection:
dojo.connect(someDomNode, "onclick", myDrawing, "addPoint");
// or:
dojo.connect(someDomNode, "onclick", myDrawing, myDrawing.addPoint);
// the surface connection:
surface.connect("onclick", myDrawing, "addPoint");
// or:
surface.connect("onclick", myDrawing, myDrawing.addPoint);
或者,您始终可以使用dojo.hitch()来使用闭包绑定上下文/范围(通过上面的示例完成:
var boundMethod = dojo.hitch(myDrawing, "addPoint");
// or:
//var boundMethod = dojo.hitch(myDrawing, myDrawing.addPoint);
// and now you can do like you did originally:
dojo.connect(someDomNode, boundMethod);
// or:
surface.connect("onclick", boundMethod);
在文档中阅读所有相关内容:
> http://dojotoolkit.org/reference-guide/quickstart/events.html#quickstart-events
> http://dojotoolkit.org/reference-guide/dojo/connect.html
> http://dojotoolkit.org/reference-guide/dojo/hitch.html
> http://dojotoolkit.org/reference-guide/dojox/gfx.html#event-processing
> http://dojotoolkit.org/api/#connect
> http://dojotoolkit.org/api/#hitch
> http://dojocampus.org/content/2008/03/15/jammastergoat-dojohitch/
> http://dojocampus.org/content/2008/07/15/dojohitch-and-scope-again/
原文地址:https://codeday.me/bug/20190627/1299517.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。