jQuery-ui: How do I access options from inside pri

2019-08-01 03:42发布

问题:

I am learning to write jquery-ui plugins using the widget-factory pattern. For cleaner organization, I have some helper methods defined inside the object literal that is passed to $.widget. I would like to access the options object in those helpers. For example in the boilerplate below, how do I access the options object inside _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 );

Thank you.

回答1:

So you're doing this inside your _create:

$(some_selector).click(this._helper)

and you want this inside the _helper to be the this on this._helper (i.e. your widget).

There are various solutions:

  1. You could use $.proxy

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

    Underscore also has _.bind and there's a native Function.bind if you don't have to worry about JavaScript version issues). Other libraries will have their own function binding tools. You already have jQuery in play so $.proxy is already available and portable as well.

  2. You could use the standard var _this = this; trick proxy the _helper call yourself:

    var _this = this;
    $(some_selector).click(function() { _this._helper() });
    
  3. You could use the eventData form of click:

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

    and then in _helper:

    _helper: function(ev) {
        var self = ev.data.self;
        // 'self' is the 'this' you're looking for.
        ...
    }