about "this" in jquery object

code like this

    var test = function (e,name) {
        this.e = e;
        this.name = name;
        this.init();
    };
    test.prototype.init = function () {
        var $e = $(this.e);
        var _this = this;
        $e.click(function () {
            alert(_this.name);
            //show the current name
        });
        $('#AA').click(function () {
            alert(_this.name);
            //show all the name
        })
    };
    new test($("#A"),"A");
    new test($("#B"),"B");

why click "$e" only show the current name, click "$('#AA')" show all the name. jsfiddle thanks!

Answers


Because the click handler for #AA is attached twice.

new test($("#A"),"A");
new test($("#B"),"B");

You call the test constructor two times, once for #A, once for #B. init gets called two times, so

$('#AA').click(function () {
    alert(_this.name);
    //show all the name
})

will be run two times too.

In the advanced event handling model (addEventListener, jQuery uses that too of course) event handlers don't replace each other (like with the old onclick and friends), but they add up instead. So if you add the same event handler 5 times to an element, it will be run 5 times when the event triggers.


That happens because you invoke:

    $('#AA').click(function () {
        alert(_this.name);
        //show all the name
    })

both for #A and #B.

When you call: new test($("#A"),"A"); the method init is called which leads to attachment of the click callback, so when you click on #AA A will be alerted.

After that you call: new test($("#B"),"B");. This leads to call of init with different values. One more click handler is attached to #AA so when you click on the element you get two alerts.


@kapa and @Minko are correct.

One quick soluction is to use unbind() to avoid the handler being added twice:

        $('#AA').unbind("click").click(function () {
            alert(_this.name);
            //show all the name
        })

unbind() will remove the click handler if it was previously added. So we are making sure that it is added once.

EDIT: In a serious application use off() instead of unbind(). See the docs for off here.


Need Your Help

How to reload UITableView after the UISearchBar ends editing

objective-c iphone uisearchbar

I created a UISearchBar. It is working but not the way I want. If I enter any first letter on the UISearchbar and then I click on the SearchButton, it doesn't work but when I push the next control...

onKeyDown not showing dialog

android onkeydown customdialog

In my app I tried to override onKeyDown method and called custom dialog but when running onto device its not showing that custom dialog. I used debugger and seen that onKeyDown method is called but