简体   繁体   中英

How to refer to object in JavaScript event handler?

This question uses jQuery but the question has nothing to do with jQuery ! 这个问题使用jQuery, 但是这个问题与jQuery无关

Okay so I have this object:

var box = new BigBox();

This object has a method named Serialize() :

box.AddToPage();

Here is the method AddToPage() :

function AddToPage()
{
    $('#some_item').html("<div id='box' onclick='this.OnClick()'></div>");
}

The problem above is the this.OnClick() (which obviously does not work). I need the onclick handler to invoke a member of the BigBox class. How can I do this?

How can an object refer to itself in an event handler?

You should attach the handler using jQuery:

function AddToPage()
{
    var self = this;
    $('#some_item').empty().append(
        $("<div id='box'></div>")
            .click(function() { self.OnClick(someParameter); })
    );
}

In order to force the event handler to be called on the context of your object (and to pass parameters), you need to add an anonymous function that calls the handler correctly. Otherwise, the this keyword in the handler will refer to the DOM element.

Don't add event handlers with inline code.

function AddToPage()
{
    $('#some_item').html("<div id='box'></div>");
    $('#box').click(this.OnClick);
}

EDIT :

Another way (avoids the extra select):

function AddToPage()
{
    var div = $('<div id="box"></div>'); // probably don't need ID anymore..
    div.click(this.OnClick);

    $('#some_item').append(div);
}

EDIT (in response to "how to pass parameters");

I'm not sure what params you want to pass, but..

function AddToPage()
{
    var self = this, div = $('<div></div>');
    div.click(function (eventObj) {
        self.OnClick(eventObj, your, params, here);
    });

    $('#some_item').append(div);
}

If you are using jQuery, then you can separate your code from your markup (the old seperation of concerns thing) like this

$(document).ready(function() {

  var box = new BigBox();

  $('#box').click(function() {
    box.serialize();
  });

});

You only need to add the click handler once for all divs with id of box. And because the click is an anonymous function, it gets the scope of the function it is placed in and therefore access to the box instance.

In jQuery 1.4 you could use a proxy.

BigBox.prototype.AddToPage= function () {
    var div= $('<div>', {id: box});
    div.click(jQuery.proxy(this, 'OnClick');
    div.appendTo('#some_item');
}

You can also use a manual closure:

    var that= this;
    div.click(function(event) { that.OnClick(event); });

Or, most simply of all, but requiring some help to implement in browsers that don't yet support it (it's an ECMAScript Fifth Edition feature):

    div.click(this.OnClick.bind(this));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM