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.
$('#elemId').myPluginName()
returns a jQuery object.To execute init() you have to access the Plugin object in data attribute
this will return the object
init: () {}
that can be executed$('#elemId').myPluginName().data('plugin_myPluginName').init()