Bind a click event to a method inside a class

前端 未结 1 1848
遇见更好的自我
遇见更好的自我 2021-01-20 08:13

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:

$(do         


        
1条回答
  •  感情败类
    2021-01-20 08:41

    One simple way to achieve that:

    function myObject(data){
        this.name = data;
    
        // Store a reference to your object
        var that = this;
    
        $("body").append("Test");
        $("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("Test");
        $("span").click($.proxy(this.myMethod, this)); 
    
        this.myMethod = function(){
            alert(this.name); 
        }
    }
    

    0 讨论(0)
提交回复
热议问题