Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BindAsEventListener equivalent in jQuery?

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;
}};
like image 510
Mike Fielden Avatar asked Mar 01 '23 20:03

Mike Fielden


1 Answers

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.

like image 53
taco Avatar answered Mar 05 '23 18:03

taco