【问题标题】:jQuery-ui: How do I access options from inside private functionsjQuery-ui:如何从私有函数内部访问选项
【发布时间】:2012-08-08 19:16:49
【问题描述】:

我正在学习使用小部件工厂模式编写 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 );

谢谢。

【问题讨论】:

  • 小部件工厂不认为带有前导下划线的方法是私有的吗?那你怎么打电话给_helper
  • 嗯,在 _create 方法中,this 指向对象字面量(第二个参数指向 $.widget),因此可以在 _create 中调用 this._helper()
  • 但是你说 '"this" 指向 dom 元素' 那么._helper() 调用是什么样的呢?而_create 是一个特殊的方法,它是小部件界面的一部分。
  • _helper 实际上是在 _create 中设置的“点击”事件的处理程序,如下所示:$(some_selector).click(this._helper)。因此,事件子系统在 DOM 元素上调用它。我正在寻找一种在 _helper 中使用 options 属性的方法。

标签: jquery-ui jquery-ui-plugins jquery-ui-widget-factory


【解决方案1】:

所以你在你的 _create 里面做这个:

$(some_selector).click(this._helper)

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

有多种解决方案:

  1. 你可以使用$.proxy

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

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

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

    var _this = this;
    $(some_selector).click(function() { _this._helper() });
    
  3. 你可以使用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.
        ...
    }
    

【讨论】:

  • 与此同时,我尝试将选项作为 event.data 的一部分传递给绑定,并且按预期工作。但是感谢代理解决方案 - 它帮助我为我不断增长的 jquery 技能增加了一个技巧:)。已接受您的回答
  • @Ya.Perelman:对,eventData 是另一种选择,为了完整起见,我将添加它。我最近做了很多 Backbone 的事情,所以我的大脑总是在寻找绑定解决方案。
猜你喜欢
  • 2016-08-04
  • 2021-08-27
  • 2011-12-29
  • 1970-01-01
  • 2014-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多