Search code examples
jqueryamd

Why is this plugin pattern not return wjat I would expect?


I'm trying to create a jQuery plugin using a modular pattern so I can use it with requirejs. I was expecting the code below to behave one way and it doesn't. I'm hoping that if someone can explain to me why it's not returning what I think it should I will help me understand. here's the code:

define(['jquery'], function($){

'use strict';

var pluginName = "myPluginName";

var Plugin = function( element, options ) {

    var _init = function() {
        console.log("hey");
    }

    return  {
        init: _init;
    }

}

$.fn[pluginName] = function ( options ) {
    return this.each(function () {
        if (!$.data(this, "plugin_" + pluginName)) {
            $.data(this, "plugin_" + pluginName,
            new Plugin( this, options ));
        }
    });
};});

Now with the above I was expecting that this would log "hey"

$('#elemId').myPluginName().init() //returns a jquery object

Any explanation would be appreciated. Thanks.


Solution

  • $('#elemId').myPluginName() returns a jQuery object.

    To execute init() you have to access the Plugin object in data attribute

    $('#elemId').myPluginName().data('plugin_myPluginName')
    

    this will return the object init: () {} that can be executed $('#elemId').myPluginName().data('plugin_myPluginName').init()

    var pluginName = "myPluginName";
    
    var Plugin = function( element, options ) {
    
        var _init = function() {
            console.log("hey");
        }
    
        return  {
            init: _init
        }
    
    }
    
    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName,
                new Plugin( this, options ));
            }
        });
    };
    
    console.log($('body').myPluginName().data('plugin_myPluginName'));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>