2014-07-14 2 views
2

나는 js-class를 가지고 있고 click 이벤트에서 jquery의 $ (this)와 object를 사용하려고한다.

jquery의 $ (this)는 잘 작동하지만 객체는 정의되지 않았습니다. 내가 첨부 된 버튼을 클릭하면

var myclass = function(){ 

    this.myfunction = function(){ 
     alert('myfunction'); 
    } 

    this.buttonclicked = function(){ 
     alert('buttonclicked'); 
    } 

    this.writeout = function(){ 
     var buttoncode = '<button class="mybutton">click</button>'; 
     $('body').append(buttoncode); 

     $('.mybutton').click(function(){ 
      alert('Button: '+$(this).attr('class')); 
      this.buttonclicked(); 
     }); 

     this.myfunction(); 
    } 

} 


var x = new myclass(); 
x.writeout(); 

http://jsfiddle.net/j33Fx/2/

, 난 버튼의 클래스와 경고를 얻을 수 있지만, 내 기능은 "this.buttonclicked"함수가 될하지 않는 것 같다.

아이디어가 있으십니까?

답변

9

this은 이벤트 처리기에서 이벤트를 호출 한 요소를 참조합니다. 현재 객체를 다른 변수에 캐시 할 수 있습니다. 후자로 사용할 수 있습니다.

사용

this.writeout = function(){ 
    var buttoncode = '<button class="mybutton">click</button>'; 
    $('body').append(buttoncode); 

    var _self = this; //cache current object 

    $('.mybutton').click(function(){ 
     alert('Button: '+ $(this).attr('class')); //Here this refers to element which invoked the event. 

     _self.buttonclicked(); //Use cached object 
    }); 

    this.myfunction(); 
} 

Updated Fiddle

+0

) (클릭 전달 된 콜백 함수를 사용하여 큰 otherClass 객체의 메소드 때이를 해결하는 방법이 "이"내부 참조하려고 다른 클래스? –

+1

@JoseOspina, 정확한 문제는 모르겠지만 [Function.prototype.bind()] (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/)에서 살펴볼 수 있습니다. Global_objects/Function/bind) – Satpal

+0

잘 작동합니다! 이제 모든 앱을 리팩토링해야합니다. 재밌네! 감사! (내 말은, 현실을 위해 : 나는 이것을 극복하기 위해 못생긴 일을하고 있었다 ... 감사합니다) –