如何从事件函数中访问其他方法?

时间:2013-03-21 09:38:46

标签: jquery design-patterns scoping

我开始更多地了解jQuery插件模式,但我遇到了一些问题。见下面的代码。我想通过onclick函数访问我的插件选项/默认值,但我不确定如何。

function SomePlugin(element,options)
{
    this.$el = $(element);

    this.options = $.extend({},
    {
        button: '#button',
        someVariable:'fuu',
        anotherVariable:'bar'

    },options);

    this.init();
}

SomePlugin.prototype =
{
    init:function()
    {
        var button = this.$el.find(this.options.button)

        button.on('click', this.onClick);
    },
    onClick: function(event){
        // Need to access the options (someVariable, anotherVariable) here... how?
    }
};


$.fn.somePlugin = function(options)
{
    return this.each(function()
    {
        if( !$.data(this,'somePlugin') )
        {
            $.data(this,'somePlugin',new SomePlugin(this,options));
        }
    });
};

我已尝试过以下代码,但出于某种原因,这感觉不对。有没有更好的办法?另外,我有关于我的插件结构的任何其他建议或提示,请告诉我。顺便说一下,为了便于阅读,我遗漏了jQuery包装器

function SomePlugin(element,options)
{
    this.el = element;
    this.$el = $(element);

    this.options = $.extend({},
    {
        button: '#button',
        someVariable:'fuu',
        anotherVariable:'bar'

    },options);

    this.init();
}

SomePlugin.prototype =
{
    init:function()
    {
        var button = this.$el.find(this.options.button)

        button.on('click', {instance:this}, this.onClick);
    },
    onClick: function(event){
        // Options can be accessed using event.data.instance.options ... is there an easier way?
    }
};


$.fn.somePlugin = function(options)
{
    return this.each(function()
    {
        if( !$.data(this,'somePlugin') )
        {
            $.data(this,'somePlugin',new SomePlugin(this,options));
        }
    });
};

2 个答案:

答案 0 :(得分:1)

当我想学习写作或理解插件时,我使用了jeffery way tuts,它确实有效。值得一看。 请尝试以下链接

https://tutsplus.com/lesson/head-first-into-plugin-development/

答案 1 :(得分:0)

我已经回答了我自己的问题。诀窍是使用jQuery的$ .proxy()方法,如下所示:

button.on('click', $.proxy(this.onClick), this);

并引用单击的按钮(因为'this'现在指的是SomePlugin类):

onClick: function(event){
    // This now refers to SomePlugin class, yay!
    // Use event.target instead of this to refer to the clicked element
    $(event.target).text(this.options.someVariable); 
}