I am trying to bind a click event to some element using jQuery.
Using prototype I know I can do this using BindAsEventListener()
.
Example:
var myObject = {
init: function(txtOneId, txtTwoId, lblResultId, ancAddId) {
this.txtOneId = txtOneId;
this.txtTwoId = txtTwoId;
this.lblResultId = lblResultId;
this.ancAddId = ancAddId;
var addListener = this.addResult.bindAsEventListener(this);
Event.observe(this.txtOneId, 'keyup', addListener);
Event.observe(this.txtTwoId, 'keyup', addListener);
},
addResult: function() {
var valueOne = $(this.txtOneId).value;
var valueTwo = $(this.txtTwoId).value;
if (isNaN(valueOne) || valueOne == "")
valueOne = 0;
else
valueOne = parseInt(valueOne);
if (isNaN(valueTwo) || valueTwo == "")
valueTwo = 0;
else
valueTwo = parseInt(valueTwo);
var result = valueOne + valueTwo;
$(this.lblResultId).innerHTML = result;
return false;
}};
I assume that you are still using prototype, and have added the jQuery no conflict so that $() is a prototype method and $j() is a jQuery method.
Quick Answer
You only need to make a change on your init method.
init: function(txtOneId, txtTwoId, lblResultId, ancAddId) {
this.txtOneId = txtOneId;
this.txtTwoId = txtTwoId;
this.lblResultId = lblResultId;
this.ancAddId = ancAddId;
var handler = function(event){ event.data.addResult(event) };
$j(this.txtOneId).bind('keyup', this, handler);
$j(this.txtTwoId).bind('keyup', this, handler);
}
Explanation
With Prototype you used the bindAsEventListener function so that the this reference will be available when the event is received.
For jQuery you can pass this event data with the bind method using the following syntax (from jquery api):
.bind( eventType [, eventData], handler(eventObject) );
Applied to your code, with the use of an anonymous function, this resolves to:
$j(this.txtOneId).bind('keyup', this, function(event){ event.data.addResult(event) });
In this case we bind the 'keyup' event to the text elements, pass the this reference as eventData and then in the handler function we reference the eventData (this) with event.data to execute the this.addResult(event) method.
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