2013-04-18 3 views
0

괜찮 았던 지 잘 모르겠다.jquery 선택기와 이벤트를 사용하여 javascript 객체의 함수 호출

저는 아약스 데이터를 기반으로 HTML을 그리는 javascript 개체가 있습니다.

그런 다음 jquery를 사용하여 위 개체의 인스턴스에서 html 출력에 대한 이벤트를 처리하려고합니다. 그러나 나는 함수를 호출하고 html을 그리는 데 사용 된 javascript 객체의 인스턴스에서 속성을 가져오고 싶습니다.

// jquery to handle events 
$(document).ready(function(){ 

// .edit is a class in the html outputted from the drawhtml 
    $('body').on('click','.edit',function() { 
    instance1.dosomething(); 
    }); 

}); 

// create instance of object could be multiple on on page 
var instance1 = new obj1(); // added parentesis so it's valid javascript 

instance1.drawhtml(); 

편집 : 당신이 이전에 생성 된 당신은 단지 인스턴스를 사용할 수 있습니다

답변

2

function obj1(){ 
    this.property1 = "propvalue"; 


    this.dosomething = function() { 
     // does some processing 
    } 

    this.drawhtml = function() { 
    // outputs html 
    } 

} 

// jquery to handle events 
$(document).ready(function(){ 

// .edit is a class in the html outputted from the drawhtml 
    $('body').on('click','.edit',function() { 
    // call the dosomething from the object 
    }); 

}); 

// create instance of object could be multiple on on page 
var instance1 = new obj1; 

instance1.drawhtml(); 

감사 : 추가 정보부터

그래서 내 코드는 다음과 같이 보입니다 의견 :

이 문제를 해결하는 가장 좋은 방법은 이벤트 처리기를 객체 자체에 연결하는 것입니다. 이런 식으로 뭔가 :

function obj1(){ 
    this.property1 = "propvalue"; 


    this.dosomething = function() { 
     // does some processing 
    } 

    this.drawhtml = function() { 
     var elem = $("<div>my super dooper HTML</div>"); 
     elem.on('click', this.dosomething); 
    } 

}

+0

네, 당신의 INSTANCE1는 전역 범위에있을 것입니다. 문제없이 로컬 jQuery 범위에서 사용할 수 있습니다. 그러나 왜 그런 식으로해야합니까? –

+0

만약 내가이 객체들 중 하나를 가지고 있다면 작동 할 것이지만 만약 내가 2를 가졌다면 – user2297026

+0

그리고 나서'instance2'를 생성하고 적절한 인스턴스에서 메소드를 호출 할 것입니다. – Kenneth

관련 문제