jQuery-ui: How do I access options from inside private functions

心已入冬 提交于 2019-12-13 18:00:24

问题


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.
        ...
    }
    


来源:https://stackoverflow.com/questions/11919412/jquery-ui-how-do-i-access-options-from-inside-private-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!