将click事件绑定到类中的方法 [英] Bind a click event to a method inside a class

查看:166
本文介绍了将click事件绑定到类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的对象的构造函数中,我创建了一些span标记,我需要将它们引用到同一个对象的方法。

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
    }

}

这个调用该方法的代码,但它不是对象的引用(this.name 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?

非常感谢!

推荐答案

实现这一目标的一种简单方法:

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); 
    }
}

另一种方法,使用 $。proxy

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); 
    }
}

这篇关于将click事件绑定到类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆