1

I don't really understand how to set listeners in my JavaScript object. For example:

var obj = function(){

    this.test = function(){
        console.log('test');
    }

    $(document).on('click','#test',(function(){
        this.test();
    }).bind(this));
}

But jQuery gives me this error

Uncaught TypeError: Object #test has no method 'apply' 

I think there is a proper way but I can't find.

Thanks for your help.

Edit: I don't know really why it works in my example but not in my code

http://jsfiddle.net/nhJNH/

4

1 回答 1

2

尝试

var obj = function(){

    this.test = function(){
        console.log('test');
    }
    var t = this;

    $(document).on('click','#test', function(){
        t.test();
    });

}

你也可以使用

$(document).on('click','#test', $.proxy(this.test, this));

或者

$(document).on('click','#test', $.proxy(function () {
    this.test();
}, this));
于 2013-07-28T10:12:00.263 回答