views:

138

answers:

2

Hi All,

I am working on the new Palm Pre WebOS, the Apps for Palm Pre are developed in MojoSDK which is developed on top of Prototype Javascript Framework.

I am trying to access variables defined at assistant level in event handlers which are a part of the same assistant as well. When I access the assistant level variables in an event handler, I get it as undefined. However, the variables are accessible in the setup function.

For reference, have a look at the Code below:

Code:

function MyTestAssistant(passedValue)
{
    this.passedValue = passedValue;
}

MyTestAssistant.prototype.setup = function()
{
    Mojo.Log.info("Passed Value Is: " + this.passedValue); // Prints the value set in Constructor
}

MyTestAssistant.prototype.testListTapHandler = function(event)
{
    Mojo.Log.info("Passed Value Is: " + this.passedValue); // Logs undefined
}

Anyone else is having this issue or I am doing something wrong here. Is it possible to access the variables in handler or we have think of workarounds to achieve it.

Looking forward to get a reply soon.

Thanks and Regards,

Muhammad Haseeb Khan

+2  A: 

I'm not familiar with mojo-sdk, but this sounds a lot like you've just got your "this" reference mixed up when you set up the event handler. In all likelihood, when testListTapHandler is called, this references the object which is firing the event.

Prototype has the very handy bind() method to help clear up this confusion though.

I'll guess you had something like this

elem.observe('eventname', myTestAssistant.testListTapHandler);

Trouble is, when the event is fired, inside testListTapHandler, this will refer to elem. To correct this, we bind the event handler with the desired object:

elem.observe('eventname', myTestAssistant.testListTapHandler.bind(myTestAssistant));
Paul Dixon
A: 

I have found the solution to the problem. Another Forum helped me as well.

The core issue, as pointed out by Paul is of Binding and Scope.

I updated my implementation to the following for making it work:

function MyTestAssistant(passedValue)
{
    this.passedValue = passedValue;
}

MyTestAssistant.prototype.setup = function()
{
    Mojo.Log.info("Passed Value Is: " + this.passedValue); // Prints the value set in Constructor

    // Was Using the following code before and this.passedValue wasn't accessible in 
    // testListTapHandler

    // Mojo.Event.listen(this.testList, Mojo.Event.listTap, this.testListTapHandler);

    // Used the following code now and this.passedValue is accessible in 
    // testListTapHandler

    this.testListTapHandler = this.testListTapHandler.bindAsEventListener(this);
    Mojo.Event.listen(this.testList, Mojo.Event.listTap, this.testListTapHandler);  
}

MyTestAssistant.prototype.testListTapHandler = function(event)
{
    Mojo.Log.info("Passed Value Is: " + this.passedValue); // Prints the value set in Constructor
}

Thanks for your help Paul.

Regards,

Muhammad Haseeb Khan

Haseeb Khan