Program Tip

jQuery 이벤트에서 'this'의 값 제어

programtip 2020. 10. 25. 12:50
반응형

jQuery 이벤트에서 'this'의 값 제어


jQuery를 사용하여 '컨트롤'을 만들고 jQuery.extend를 사용하여 가능한 한 OO로 만드는 데 도움을주었습니다.

컨트롤을 초기화하는 동안 다음과 같이 다양한 클릭 이벤트를 연결합니다.

jQuery('#available input', 
            this.controlDiv).bind('click', this, this.availableCategoryClick);

bind 메서드에서 데이터 인수로 'this'를 사용하고 있음을 주목하십시오. 클릭 이벤트를 발생시키는 요소가 아닌 컨트롤 인스턴스에 연결된 데이터를 가져올 수 있도록 이렇게합니다.

이것은 완벽하게 작동하지만 더 나은 방법이 있다고 생각합니다.

과거에 Prototype을 사용해 왔지만 이벤트에서 'this'의 값을 제어 할 수있는 바인드 구문을 기억합니다.

jQuery 방식은 무엇입니까?


jQuery.proxy()익명 함수와 함께 사용할 수 있지만 'context'가 두 번째 매개 변수라는 점이 조금 어색합니다.

 $("#button").click($.proxy(function () {
     //use original 'this'
 },this));

나는 당신의 방식을 좋아합니다. 사실 비슷한 구조를 사용합니다.

$('#available_input').bind('click', {self:this}, this.onClick);

this.onClick의 첫 번째 줄 :

var self = event.data.self;

이렇게하면 클로저를 사용할 필요없이 요소를 클릭 (이렇게)하고 "this"개체를 self로 만들 수 있기 때문에이 방식을 좋아합니다.


jQuery에는 jQuery.proxy메서드가 있습니다 (1.4부터 사용 가능).

예:

var Foo = {
  name: "foo",

  test: function() {
    alert(this.name)
  }
}

$("#test").click($.proxy(Foo.test, Foo))
// "foo" alerted

나는 jQuery에 내장 기능이 있다고 생각하지 않는다. 그러나 다음과 같은 도우미 구성을 사용할 수 있습니다.

Function.prototype.createDelegate = function(scope) {
    var fn = this;
    return function() {
        // Forward to the original function using 'scope' as 'this'.
        return fn.apply(scope, arguments);
    }
}

// Then:
$(...).bind(..., obj.method.createDelegate(obj));

이런 식으로 주어진 객체를 'this'범위로 사용하여 메서드를 호출하는 createDelegate ()로 동적 '래퍼 함수'를 만들 수 있습니다.

예:

function foo() {
    alert(this);
}

var myfoo = foo.createDelegate("foobar");
myfoo(); // calls foo() with this = "foobar"

HTML 5 호환 브라우저는 아마도 가장 깨끗한 구문이며 프레임 워크에 종속되지 않는 바인드 메소드제공합니다 Function.prototype.하지만 IE 9까지는 IE에 내장되지 않았습니다 (하지만 그것이없는 브라우저를위한 폴리 필 이 있습니다).

귀하의 예를 기반으로 다음과 같이 사용할 수 있습니다.

jQuery('#available input', 
        this.controlDiv).bind('click', this.availableCategoryClick.bind(this));

(side note: the first bind in this statement is part of jQuery and has nothing to do with Function.prototype.bind)

Or to use slightly more concise and up-to-date jQuery (and eliminate confusion from two different kinds of binds):

$('#available input', this.controlDiv).click(this.availableCategoryClick.bind(this));

you can use the javascript bind method like this:

var coolFunction = function(){
  // here whatever involving this
     alert(this.coolValue);
}

var object = {coolValue: "bla"};


$("#bla").bind('click', coolFunction.bind(object));

jQuery does not support binds and the preferred way is to use functions.

Because in Javascript, this.availableCategoryClick does not mean calling the availableCategoryClick function on this object, jQuery advise to use this preferred syntax:

var self = this;
jQuery('#available input', self.controlDiv).bind('click', function(event)
{
   self.availableCategoryClick(event);
});

OO concepts in Javascript are hard to understand, functionnal programming is often easier and more readable.


Seeing that functions changes scope, the most common way is to do it by hand, with something like var self = this.

var self = this

$('.some_selector').each(function(){
  // refer to 'self' here
}

참고URL : https://stackoverflow.com/questions/520019/controlling-the-value-of-this-in-a-jquery-event

반응형