jQuery-ui:如何从私有函数内部访问选项 [英] jQuery-ui: How do I access options from inside private functions

查看:131
本文介绍了jQuery-ui:如何从私有函数内部访问选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习使用widget-factory模式编写jquery-ui插件.对于更清洁的组织,我在传递给$.widget的对象常量中定义了一些帮助程序方法.我想访问那些帮助器中的options对象.例如,在下面的样板中,如何访问_helper()中的options对象?

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 );

谢谢.

推荐答案

因此,您正在_create中进行此操作:

So you're doing this inside your _create:

$(some_selector).click(this._helper)

,并且您希望_helper中的this成为this._helper上的this(即您的小部件).

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

有多种解决方案:

  1. 您可以使用 $.proxy

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

Underscore还具有 _.bind ,并且还有一个本地

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.

您可以使用标准的var _this = this;技巧代理_helper自己呼叫:

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

var _this = this;
$(some_selector).click(function() { _this._helper() });

  • 您可以使用 eventData形式的click :

  • You could use the eventData form of 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.
        ...
    }
    

  • 这篇关于jQuery-ui:如何从私有函数内部访问选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆