English 中文(简体)
How to refer to object in JavaScript event handler?
原标题:

Note: This question uses jQuery but the question has nothing to do with 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?

最佳回答

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);
}
问题回答

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.

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));

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.





相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签