Calling object methods inside dojo

I am trying to create a dojo class that contains functions that in turn call other functions in this class, as follows:

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 } }); 

The above (trimmed) code should add a dot to the dojo.gfx surface. When I try to start it, I get the following console error:

 Uncaught TypeError: Object #<an HTMLDivElement> has no method 'addAbsPoint' 

The addPoint (event) function is called correctly, but it fails when it tries to reference the addAbsPoint (x, y) function in the same object. Is this possible in dojo? How can i do this?

+4
source share
1 answer

addPoint() not being called correctly, and not in the correct context. Judging by his signature, my psychic abilities tell me that you use it as an event handler, but you are not doing it right.

You do it like this:

 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); 

In JavaScript, the above lines pass a function, not a binding method, as you would expect. You need to pass the context (the object to call the function):

 // 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); 

Alternatively, you can always use dojo.hitch() to link the context / area using closure (which is done by the above examples:

 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); 

Read all about this in the documentation:

+3
source

Source: https://habr.com/ru/post/1314866/


All Articles