Skip to content Skip to sidebar Skip to footer

Jquery Plugin + Amd = How To Access Functions?

I am wrapping up my jQuery plugin in an AMD environment. This is my boilerplate, !function(root, factory) { if (typeof define === 'function' && define.amd) { de

Solution 1:

You don't seem to be actually creating an instance of myPlugin, instead you're trying to access the methods statically which may or may not be what you're after.

I find it better to create an instance of my Plugin object for each time the plugin is used. An example:

!function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else {
        factory(root.jQuery);
    }
}(this, function($) {
    'use strict';

    var defaults = {

    };

    varPlugin = function(element, options) {
        this.element = element;
        this.options   = options;
    };

    Plugin.prototype = {
        constructor: Plugin,

        someMethod: function() {

        }
    }

    // Create the jQuery plugin
    $.fn.plugin = function(options) {
        options = $.extend(true, {}, defaults, options);

        returnthis.each(function() {
            var $this = $(this);
            $this.data('plugin', newPlugin($this, options));
        });
    };

    // Expose defaults and Constructor
    $.fn.plugin.defaults = defaults;
    $.fn.plugin.Plugin   = Plugin;
});

From here - https://gist.github.com/simonsmith/4353587

Now you could use the plugin like this:

require(['jquery', 'jquery.plugin'], function($) {
    $('.test li').plugin({
        test: 'option1',
        test2: 'option2'
    });
});

An instance of the object is saved in a data property, so it can always be accessed. Herotabs uses this technique:

var instance = $('.tabs').herotabs().data('herotabs');
instance.nextTab();

Solution 2:

var plugin = $('.element').plugin();
    var instance = $('.element').data('plugin');
    console.log(instance);
    console.log(instance.someMethod("hello world"));

result,

Object { element={...}, options={...}, constructor=function(), more...}

hello world

Post a Comment for "Jquery Plugin + Amd = How To Access Functions?"