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