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);
});
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With