Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

javascript - Bind a click event to a method inside a class

In the constructor of my object, I create some span tag and I need to refers them to a method of the same object.

Here is an example of my code:

$(document).ready(function(){
    var slider = new myObject("name");
});

function myObject(data){
    this.name = data;

    //Add a span tag, and the onclick must refer to the object's method
    $("body").append("<span>Test</span>");
    $("span").click(function(){
        myMethod(); //I want to exec the method of the current object
    }); 


    this.myMethod = myMethod;
    function myMethod(){
        alert(this.name); //This show undefined
    }

}

With this code the method is called, but it is not a reference to the object (this.name show undefined) How can I resolve that?

Thanks a lot!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One simple way to achieve that:

function myObject(data){
    this.name = data;

    // Store a reference to your object
    var that = this;

    $("body").append("<span>Test</span>");
    $("span").click(function(){
        that.myMethod(); // Execute in the context of your object
    }); 

    this.myMethod = function(){
        alert(this.name); 
    }
}

Another way, using $.proxy:

function myObject(data){
    this.name = data;

    $("body").append("<span>Test</span>");
    $("span").click($.proxy(this.myMethod, this)); 

    this.myMethod = function(){
        alert(this.name); 
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...