Frage

I'm starting to learn more about jQuery plugin patterns, but I've run into something. See code below. I want to access my plugins options/defaults from with an onclick function, but I'm not sure how.

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

I've tried the code below, but this doesn't feel right for some reason. Is there a better way? Also I you have any other suggesties or tips regarding my plugin structure, please let me know. BTW I've left out the jQuery wrapper for readability

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));
        }
    });
};
War es hilfreich?

Lösung 2

I've answered my own question. The trick was to use jQuery's $.proxy() method like this:

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

And to refer to the clicked button (since 'this' now refers to SomePlugin class):

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

Andere Tipps

When i wanted to learn writing or understanding plugin i used jeffery way tuts and it really works. Worth looking once. Try below link

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top