tags:

views:

32

answers:

1

I am trying to create a dojo class which contains functions which in turn call other functions within 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 is to add a point onto a dojo.gfx surface. When I try and run it I get the following console error:

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

The function addPoint(event) is being called correctly, but it fails when it trys to reference the function addAbsPoint(x,y) in the same object. Is this possible in dojo? Can anyone suggest a way to accomplish it?

+2  A: 

addPoint() is not called correctly, not in the right context. Judging by its signature my psychic abilities tell me that you use it as an event handler, but you don't do it correctly.

You do it like that:

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 bound method as you would expect. You need to pass a context (an object to call a function on):

// 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 bound the context/scope using a closure (which is done by examples above:

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 it in the documentation:

Eugene Lazutkin
Excellent, thanks for the quick, complete and concise response. This worked completely. I completely overlooked the event handling side because the error occurred trying to access the second method, hopefully not a mistake I'll be making again soon!
spikeheap
also worth pointing out the use of the variable `container` in the above addPoint function has no source. It should likely be this.container
dante