2016-10-21 2 views
1

를 클릭 나는 다음과 같은 방법 console.log(self), 그것은 방법 PMm.test을 반환액세스는 특정 요소가

PMm.test = function(){ 
    ....plenty of code.... 

    $('.element',this.page).click(function(e){ 
    e.preventDefault(); 
    var self = $(this); 
    console.log(self); 
    this.load(someoptions) 
    }.bind(this)); 

    ...plenty of code.... 

} 

PMm.test.prototype.load = function(options){ 
    ...some code 
} 

에게 있습니다. $(this)이 내 이벤트를 선언하는 전체 함수 범위 인 경우 클릭 한 요소에 어떻게 액세스합니까? 나중에 선언 된 .load() 메서드를 호출해야한다는 것을 알았습니다.

+1

왜 클릭 이벤트 함수의 내부는? 이들은 일반적으로 전 세계적으로 설정됩니다. 그것만으로 도움이 될 수도 ... – user1289451

답변

3

나는 그것을 생각 컨텍스트를 av에 저장하는 것이 가장 좋습니다. 콜백에서 클로저를 사용하여 액세스 할 수 있습니다. 더 읽기 쉬운 코드로 이어질 것입니다.

PMm.test = function(){ 
    ....plenty of code.... 
    // Store the context in a variable.  
    var that = this; 
    $('.element',this.page).click(function(e){ 
    e.preventDefault(); 
    // this here references the DOM element (as expected) 
    var self = $(this); 
    console.log(self); 
    // you can access your methods through that. 
    that.load(someoptions) 
    }); 

    ...plenty of code.... 

} 

PMm.test.prototype.load = function(options){ 
    ...some code 
} 

희망이 있습니다.

+0

실제로 .bind (this) – Nicc

1

당신이 다른 (때문에 bind의) 뭔가 this를 사용하고 있기 때문에, 당신은 사용할 수 있습니다 :

  • e.target -이의 후손이 될 수 이벤트가 실제로 발생한 요소입니다 핸들러를 첨부 한 요소.

    또는

  • e.currentTarget

    -이 핸들러에 부착되어있는 소자이다. (당신이 bind를 사용하지 않으면 어떻게 jQuery를 콜백에서 일반적으로 this입니다.)

예 :

PMm.test = function(){ 
    // ....plenty of code.... 

    $('.element',this.page).click(function(e){ 
    e.preventDefault(); 
    var elementClicked = $(e.currentTarget); // or $(e.target); 
    // ...use it... 
    this.load(someoptions) 
    }.bind(this)); 

예 :

function ClickResponder(name, selector) { 
 
    this.name = name; 
 
    $(selector).on("click", this.handler.bind(this)); 
 
} 
 
ClickResponder.prototype.handler = function(e) { 
 
    console.log("this.name = " + this.name); 
 
    console.log("e.target.tagName = " + e.target.tagName); 
 
    console.log("e.currentTarget.tagName = " + e.currentTarget.tagName); 
 
}; 
 
new ClickResponder("respond-o-matic", ".foo");
<div> 
 
    <div class="foo"> 
 
    <span>Click me</span> 
 
    </div> 
 
    <div class="foo"> 
 
    <span>Click me</span> 
 
    </div> 
 
</div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1

[function].bind(this)을 사용하면 jquery 이벤트에 this (PMm.test)을 바인딩하고 jquery로 this (요소)을 덮어 씁니다. 당신은 함수 내에서 모두를해야 할 경우 개체 PMm.test가 accesible 변수를 사용하여 만드는 대신, 객체를 바인딩 할 필요가 없습니다 :

PMm.test = function(){ 
    ....plenty of code.... 

    var obj=this; //obj references to PMm.test 

    $('.element',this.page).click(function(e){ 
    e.preventDefault(); 
    var self = $(this); 
    console.log(self); 
    obj.load(someoptions) 
    }); //no .bind() 

    ...plenty of code.... 

} 

PMm.test.prototype.load = function(options){ 
    ...some code 
}