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/

2

1 Answer 1

2

Try

var obj = function(){

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

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

}

You may also use

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

or

$(document).on('click','#test', $.proxy(function () {
    this.test();
}, this));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.