1

我正在学习使用小部件工厂模式编写 jquery-ui 插件。为了更简洁的组织,我在传递给 $.widget. 我想访问这些助手中的选项对象。例如在下面的样板中,我如何访问里面的选项对象_helper()

;(function ( $, window, document, undefined ) {

    $.widget( "namespace.widgetName" , {

        options: {
            someValue: null
        },

        _create: function () {
            // initialize something....
        },

        destroy: function () {

            $.Widget.prototype.destroy.call(this);
        },

        _helper: function () {
            // I want to access options here.
            // "this" points to the dom element, 
            // not this object literal, therefore this.options wont work
            console.log('methodB called');
        },

        _setOption: function ( key, value ) {
            switch (key) {
            case "someValue":
                //this.options.someValue = doSomethingWith( value );
                break;
            default:
                //this.options[ key ] = value;
                break;
            }
            $.Widget.prototype._setOption.apply( this, arguments );
        }
    });

})( jQuery, window, document );

谢谢你。

4

1 回答 1

1

所以你在你的内部这样做_create

$(some_selector).click(this._helper)

并且您希望this在内部_helper成为thison this._helper(即您的小部件)。

有多种解决方案:

  1. 你可以使用$.proxy

    $(some_selector).click($.bind(this._helper, this));
    

    如果您不必担心 JavaScript 版本问题,Underscore 也有_.bind并且有一个本机)。Function.bind其他库将拥有自己的函数绑定工具。您已经使用了 jQuery,因此$.proxy它也已经可用且可移植。

  2. 您可以自己使用标准var _this = this;技巧代理_helper调用:

    var _this = this;
    $(some_selector).click(function() { _this._helper() });
    
  3. 您可以使用以下eventData形式click

    $(some_selector).click({ self: this }, this._helper);
    

    然后在_helper

    _helper: function(ev) {
        var self = ev.data.self;
        // 'self' is the 'this' you're looking for.
        ...
    }
    
于 2012-08-12T19:19:23.747 回答