2013-06-24 2 views
2

내 객체의 생성자에서 일부 span 태그를 만들고이를 동일한 객체의 메소드로 참조해야합니다. 여기 클래스 내의 메소드에 클릭 이벤트를 바인드합니다.

내 코드의 예입니다 : 메소드가 호출이 코드

$(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 쇼) 을 참조 어떻게 그것을 해결할 수없는?

고맙습니다.

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를 사용하여 : 그것을 달성하기

+2

의 this'는 트리거 이벤트가 될 것이다 (현재 범위를 참조 할 것'때문에 즉, 클릭) –

답변

5

한 가지 간단한 방법

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

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

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

또는 방금 추가 한대로 this.name 대신 –

+0

@GokulKav 또는 $ .proxy 대신'data'를 사용할 수 있습니다. 또는 묶어 라. 여러 솔루션이 있습니다 – bfavaretto

+0

옙 .. 귀하의 솔루션을 upvoted –

관련 문제