user1529413
user1529413

Reputation: 464

How can I call a callback from a different object

This is for a game I'm writing in JavaScript. I've got an array of objects (pieces) each with multiple methods (Method_1 .. Method_N). Meanwhile I have some other function (gameAI) that determines in what order the objects should call what methods.

//Array of objects definition
function gamePiece() {
    this.CallBack = null;
    this.Method_1 = function...
    this.Method_2 = function...
    this.Method_3 = function...
    this.Method_N = function() {
        //do things...
        if( this.CallBack != null ) {
            if( this.CallBack != null) {
                // Question is here
                this.CallBack(); // <-- I do not want this.CallBack, I want that.CallBack()
            }
        }
    }
}

var pieces = new Array();
for(var i=0; i<10; i++) {
    pieces.push = new gamePiece();
}

function gameAI() {
    pieces[4].CallBack = pieces[3].Method_1;   
    pieces[3].CallBack = pieces[2].Method_2;
    pieces[2].CallBack = pieces[1].Method_1;
    pieces[4].Method_2();
}
gameAI();

So in this example:

First piece 4 calls method_2

After this completes piece 3 calls method_1

After this completes piece 2 calls method_2

After this completes piece 1 calls method_1

Since piece 1 has no callback defined nothing more occurs

The behavior I am seeing is that when piece 4 does this.Callback() it calls it from the context of itself not from the context of piece 3. So it would seem Callback stores the function to call but not the caller.

To address this I changed the code to the following:

....
snip
....
pieces[4].CallBack = ({
      Sender: pieces[3]
     ,Method: pieces[3].Method_1
});
....
snip
....
if( this.CallBack != null ) {
    this.CallBack.Sender.????
    ? perhaps some sort of ?
    this.CallBack.Method.call(this.CallBack.Sender)
}

Any ideas?

Upvotes: 0

Views: 44

Answers (2)

John Smith
John Smith

Reputation: 601

Apparently I do not have enough points to comment, so apologies to StackOverflow maintenance persons.

@raina77ow Game programming is often very complicated, the example I gave here was stripped down to just communicate the question. Each method has it's own asynchronous methods with it's own callbacks.

something like

var methodsToCall = new Array();
methodsToCall.push(...
methodsToCall.push(...
methodsToCall.push(...
...
for(var i in methodsToCall) {
    i();
}

would not work. --- Was that what you had in mind?

Upvotes: 0

Tibos
Tibos

Reputation: 27853

As raina77ow mentioned in the comment, your logic seems very complicated. Anyway, a solution to the problem you're having is to bind the method you want:

pieces[4].CallBack = pieces[3].Method_1.bind(pieces[3]);   

That will ensure that when the callback is executed, the context it runs in will be pieces[3].

Upvotes: 1

Related Questions