views:

145

answers:

1

I might be using the wrong patterns here, but if I am, I hope someone can correct me!

I have an object which represents a user's workspace and, in response to a server action, it clones a div, changes some of its properties, positions it on the workspace, makes it draggable and adds an onComplete action. This action is intended to call another method of the workspace object to send the div's updated position back to the server for layout persistence.

I've stripped the class down to the relevant methods:

var MooPanel = new Class( {
    createDiv: function() {
        var newDiv = existingDiv.clone();
        var dragHandle = newDiv.title;

        var move = new Drag(newDiv, {
            'handle':  dragHandle,
            'x': true,
            'y': true,
           /* original line: 
            'onComplete': function( el, dr ) { updateCoordinates( el, dr ); }
            */
           /* working line: */
            'onComplete': function( el, dr ) { this.updateCoords(el); }.bind(this)
        }
    },
    updateCoordinates: function( el, dr ) {
        send.to.server();
    }
});

Now, I'm having trouble getting it to call my updateCoordinates method. I've tried a variety of combinations of this and other keywords, but can't quite get it right.

What is the right way to call updateCoordinates?

A: 

Try this (pun not intended):

onComplete: function( el, dr ) { this.updateCoordinates( el, dr ) }.bind(this);

within your onComplete function this refers to the onComplete function itself. By binding the function to your class this then references the class instance itself.

Rob
Brilliant, thank you, I'd tried various combinations of `this` and `.bind(this)` but never got them right, I've edited the answer to include the correct line now, thanks!
Martin