views:

30

answers:

2
var MyObject = {
    init: function () {
        this.items = $('#menu a');

        for (var i = 0; i < this.items.length; i++) {
            $(this.items[i]).bind('click', this.doSomething);
        }
    },

    doSomething: function (index) {
        alert(this.items[index].innerHTML);
        // alerts: One, Two, Three
    }
};

I need pass the index (i)

Edit: Illustration: http://jsfiddle.net/mUjAj/

A: 

Try this and see if it works:

var MyObject = {
    init: function () {
        this.items = $('#menu a');

        for (var i = 0; i < this.items.length; i++) {
            $(this.items[i]).bind('click', {index:i}, this.doSomething);
        }
    },

    doSomething: function (e) {
        alert(e.data.index);

    }
};
Phil.Wheeler
yes, it works, just a little fix: doSomething: function (e) ..., thank you
Luistar15
I can not vote yet, but thanks again.
Luistar15
Opps, I need "this" will be MyObject, not the element "a" who fires the event.
Luistar15
+1  A: 

There's no need to pass an index here, since this will refer to the element you want clicked inside a click event handler, you can just do this:

var MyObject = {
    init: function () {
        this.items = $('#menu a');
        this.items.bind('click', this.doSomething);
    },    
    doSomething: function () {
        alert(this.innerHTML);
    }
};

You can test it out here.

Nick Craver
yes, but I need "this" will be MyObject, not the element "a" who fires the event.
Luistar15
@Luistar15 - That's just not the case in an event handler, `this` refers to the element, if you want it to refer to the element it's better to create a variable like `self` that you refer to, or change the context of the handler...but there's only one copy of your variable anyway, you can just do `MyObject` to refer to it, unless I'm missing something?
Nick Craver
I get it, yes, ther is only one copy. So, I can't do something like this (http://jsfiddle.net/mUjAj/2/) ? jquery version would be (http://jsfiddle.net/mUjAj/3/). So, is it definite that I can not use "this" to refer to "MyObject"? Or is there any way?
Luistar15
@Luistar15 - If you were using jQuery 1.4 here's what it'd look like with proxy: http://jsfiddle.net/nick_craver/mUjAj/4/ or you can do the same thing with another function, for example: http://jsfiddle.net/nick_craver/mUjAj/5/
Nick Craver
Thank you very much.
Luistar15

related questions