Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery use an object's method as an event handler

I have an object. It initializes a button to alert "Hello!" when it is clicked. Why won't this work?

jsfiddle: http://jsfiddle.net/kUT52/1/

HTML

<button>Test</button>

JS

var MyObject = {
  testValue: "Hello!",

  testFunction: function() {
    alert(this.testValue);
  },

  init: function(button) {
    button.click(this.testFunction());
  }
}

$(document).ready(function(){
  var buttonInstance = new MyObject();
  var button = $('button');
  buttonInstance.init(button);
});
like image 764
Don P Avatar asked Jun 28 '13 20:06

Don P


People also ask

Which jQuery method is used to attach a handler to an event?

Commonly Used jQuery Event Methods The click() method attaches an event handler function to an HTML element. The function is executed when the user clicks on the HTML element.

How is an event handled in jQuery?

Whenever a jQuery event is fired, jQuery passes an Event Object to every event handler function. The event object provides various useful information about the event.

What method in jQuery which is used to point a specified event handler on to a selected element?

bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.

Does jQuery have an event object?

jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler. Most properties from the original event are copied over and normalized to the new event object.


1 Answers

Whenever you put () behind a function reference, you are executing the function. You have to pass the function reference to .click, not what the function returns (unless the function returns a function that you want to use as event handler).

Example:

button.click(this.testFunction);

But now you have another problem: Inside the function, this will refer to the DOM element and not to the object, so accessing this.testValue will return undefined.

You can use jQuery's $.proxy function to fix this:

button.click($.proxy(this.testFunction, this));

Now this will refer to the object, and you can get a reference to the clicked element via event.target.

like image 57
Felix Kling Avatar answered Nov 13 '22 03:11

Felix Kling