当前位置: 动力学知识库 > 问答 > 编程问答 >

scope - How do I access class variables from an event in Javascript?

问题描述:

I'm using the prototype javascript libraries. My code is below. I've created a class and in that class I have created an event listener for one of the class methods. In that method I need to access both the attributes of the form element that triggers the event and the class properties. Currently, the code understands $(this).getValue() in the event because this is being assigned to the form element that triggered the event. How can I access the this.makingRequest and this.user properties from the event function? Can I pass them in as parameters somehow? If so, how? Nothing I've tried to this point works. Thanks for any help.

function AddressBookEntryObj(user, selectField)

{

this.selectField = selectField;

this.user = user;

this.makingRequest = false;

this.debugMode = false;

Event.observe(this.selectField, 'change', handleEvent);

}

//Prototype statements

AddressBookEntryObj.prototype.handleEvent = handleEvent;

//End prototype statements

function handleEvent()

{

try

{

if (!this.makingRequest)

{

this.makingRequest = true;

var ajax =

new Ajax.Request(

'/servlet/MyReallyCoolServlet',

{

method: 'get',

parameters: {

action: 'doGet',

whichFunc: 'MyReallyCoolFunction',

fieldValue: $(this).getValue(),

user: this.user

},

onCreate: handleAjaxCreate,

onComplete: handleChangeComplete

}

);

return true;

}

else

{

return false;

}

}

catch (ex)

{

alert("handleEvent Error: \r\n" + ex.toString());

}

}

Thanks!

Andrew

网友答案:

jsfiddle example

Take a look at this jsfiddle I made with your code. You needed to add "bind(this)" to your callback handler. Doing that will make "this" be your object and use "e.target" to access the html element.

_Michael

网友答案:

Firstly use:

AddressBookEntryObj.prototype.handleEvent = function()
{
}

Then this inside handleEvent should point to AddressBookEntryObj. To be sure it will work everywhere inside that function use something like:

var _this = this;

And then use _this inside any event handlers.

分享给朋友:
您可能感兴趣的文章:
随机阅读: