开发者

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

I'm using the prototype javascript l开发者_StackOverflow中文版ibraries. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜