문제

jQuery.widget("ui.test",{
    _init: function(){
        $(this.element).click(this.showPoint);
    },

    showPoint: function(E){
        E.stopPropagation();
        alert(this.options.dir);
    }
}

$('#someEleme').test();

Right now, the way I wrote it the options object is not defined inside the showPoint
event handler. What is the right way to pass this value in a jQuery widget?

도움이 되었습니까?

해결책

Its about the context in which the showPoint function gets called. In your case you've given the function to the jQuery event handler and this causes jQuery to call the function in the context of the event.target element. You can overwrite this using jQuery.proxy(), in your code this would look like so:

jQuery.widget("ui.test",{
    _init: function(){
        $(this.element).click($.proxy(this.showPoint, this));
    },

    showPoint: function(E){
        E.stopPropagation();
        alert(this.options.dir);
    }
}

Note that this will overwrite the this variable inside the showPoint function, so you can no longer use stuff like $(this).hide(), you will have to use $(E.target).hide() or in fact $(this.element).hide().

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top