Search code examples
javascriptjqueryrequirejsjs-amd

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) {
        define(['jquery'], factory);
    } else {
        factory(root.jQuery);
    }
}(this, function($) {

    var defaults = {
       target: ''
    };

    var myPlugin = function(options) {
        options = $.extend(true, {}, defaults, options);

        return options;
    };

    myPlugin.prototype = {
        init: function(options) {
            return options;
        }
    };

    $.fn.myPlugin = myPlugin;

});

console.log($.fn.myPlugin.init());

error,

TypeError: $.fn.myPlugin.init is not a function

console.log($.fn.myPlugin.init());

Any ideas what I have done incorrectly? And how can I access the function inside myPlugin.prototype = {...}?

EDIT:

tested with this boilerplate,

console.log($('.test li').plugin({
        test: 'option1',
        test2: 'option2'
    }));

result,

Object[] // why is it empty?

And

console.log($.fn.plugin.someMethod());

result,

TypeError: $.fn.plugin.someMethod is not a function

console.log($.fn.plugin.someMethod());

And,

// Plugin methods and shared properties
    Plugin.prototype = {
        // Reset constructor - http://goo.gl/EcWdiy
        constructor: Plugin,

        someMethod: function(options) {
            return options;
        }
    };

console.log($.fn.plugin.Plugin.prototype.someMethod("hello world"));

result,

hello world

And,

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

result,

TypeError: instance is null // what does it mean? It should return 'hello world', isn't it?

instance.someMethod("hello world");

EDIT 2:

var plugin = $('.element').plugin();
    var instance = $('.element').data('plugin',plugin);
    console.log(instance); // returns - Object[]
    console.log(instance.someMethod("hello world"));

result,

TypeError: instance.someMethod is not a function

console.log(instance.someMethod("hello world"));


Solution

  •     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