How to Create a Jquery Plugin with Methods

How to create a jQuery plugin with methods?

According to the jQuery Plugin Authoring page (http://docs.jquery.com/Plugins/Authoring), it's best not to muddy up the jQuery and jQuery.fn namespaces. They suggest this method:

(function( $ ){

var methods = {
init : function(options) {

},
show : function( ) { },// IS
hide : function( ) { },// GOOD
update : function( content ) { }// !!!
};

$.fn.tooltip = function(methodOrOptions) {
if ( methods[methodOrOptions] ) {
return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
// Default to "init"
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.tooltip' );
}
};

})( jQuery );

Basically you store your functions in an array (scoped to the wrapping function) and check for an entry if the parameter passed is a string, reverting to a default method ("init" here) if the parameter is an object (or null).

Then you can call the methods like so...

$('div').tooltip(); // calls the init method
$('div').tooltip({ // calls the init method
foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method

Javascripts "arguments" variable is an array of all the arguments passed so it works with arbitrary lengths of function parameters.

creating a jquery plugin with multiple functions

If you look at the design of some of the other jQuery plugins and jQuery UI, what they do is they have a single function $('#div').myplugin({options}), and then they can do different functions by passing a string instead of an object $('#div').myplugin('performdifferenttask') which can in turn call a helper function that is hidden from the user.

For an example look at http://jqueryui.com/demos/progressbar/#methods

Here is an example that will hopefully alleviate your confusion:

(function($) {
$.fn.myplugin = function(options) {
if(options == 'function1')
function1();
else if(options == 'function2')
function2();
else {
//do default action
}
}

function function1() {
//do something
}

function function2() {
//do something else
}
}

Then in use:

$.myplugin({option1: 4, option2: 6}); //does default behavior
$.myplugin('function1'); //calls function1()
$.myplugin('function2'); //calls function2()

How to create a javascript plugin with methods?

If you mean "how do I add my own methods to DOM element," my recommendation is: Don't, because your methods can conflict with ones added to the standard later. (And absolutely don't in a library, only do it — if you do it — in code for a specific page or application.) Instead, do what jQuery did and put wrappers around elements.

But if you want to do it anyway, you'd add functions to the prototype of the elements you want them to appear on. The base HTML element is HTMLElement, so to add a method to all HTML elements, you'd add it there.

// Ensure that your method isn't enumerable by using `Object.defineProperty`
Object.defineProperty(HTMLElement.prototype, "greenify", {
configurable: true,
writable: true,
value() {
this.style.color = "green";
}
});

Example:

// Ensure that your method isn't enumerable by using `Object.defineProperty`
Object.defineProperty(HTMLElement.prototype, "greenify", {
configurable: true,
writable: true,
value() {
this.style.color = "green";
}
});

// Use it
document.getElementById("a").greenify();
document.getElementById("b").greenify();

// Since it's on the prototype, it applies regardless of
// whether the element already existed:
const c = document.createElement("div");
c.greenify();
c.textContent = `This is "c"`;
document.body.appendChild(c);
<div id="a">This is "a"</div>
<div id="b">This is "b"</div>

How to create simple jQuery plugin?

For plugin authoring try this way, much more solid:

Edit:
Here is working jsFiddle example.


PLUGIN:

(function($){
$.fn.extend({
YourPluginName: function(options) {
var defaults = {
howMuch:'600',
animation: '',//users can set/change these values
speed: 444,
etc: ''
}
};

options = $.extend(defaults, options);

return this.each(function() {
var $this = $(this);
var button = $('a', $this);// this represents all the 'a' selectors;
// inside user's plugin definition.

button.click(function() {
$this.animate({'top':options.howMuch});//calls options howMuch value
});
});
})(jQuery);

USER'S DOCUMENT:

$(function() {
$('#plugin').YourPluginName({
howMuch:'1000' //you can give chance users to set their options for plugins
});
});

<div id="plugin">
<a>1</a>
<a>2</a>
<a>3</a>
</div>

How To Create methods(functions) in jQuery Plugins

how i can add methods in this plugin

The same way that you already do. Notice how you're adding a plugin function here:

$.fn.upload = function(options) {
//...
}

So if you want to add a function by a different name, simply add a function by a different name:

$.fn.myPlugin = function(options) {
//...
}

Create jQuery plugin with configuration settings

You're going to want to save the settings object per-element so that the settings will persist across different selectors. The best way to do this is to use jQuery.data to attach a settings object to the element. This way, the settings will persist each time the element is selected, regardless of how it is selected.

Then, in the .each call of someOtherMethod, you can access this data using jQuery.data on the element.

Also, each individual element is going to need a separate settings object to avoid overwriting shared settings, so this:

var settings = $.extend(defaults, options  || {});

Will need to be replaced with this:

var settings = $.extend({}, defaults, options  || {});

Otherwise the defaults object will be overwritten each time with new settings properties, and shared among all the elements.

In this example, I have created a variable name internalPrefix with the value of '_myPlugin' for the key under which to save the data using jQuery.data. I've added some tests at the bottom to show how it can be initialized on different ways, but the method can be called and still be aware of the settings used to initialize on the element.

#Working Example:

(function( $ ){

var defaults={
x : 123,
y : 321
};
//A variable to save the setting data under.
var internalPrefix = '_myPlugin';

var methods = {
init : function( options ) {
return this.each(function() {
//Setup the settings object.
var settings = $.extend({}, defaults, options || {});
//Save the settings to the element.
$(this).data(internalPrefix, settings);
});
},

someOtherMethod : function() {
return this.each(function() {
//Get the existing settings.
var settings = $(this).data(internalPrefix);
//Example:
$('<code></code>').text(JSON.stringify(settings)).appendTo(this);
})
},
};

$.fn.myPlugin = function(method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.myPlugin' );
}
};

}( jQuery ));

//Initialize the plugin different ways.
$('.group-1').myPlugin();
$('.group-2').myPlugin({
x : 42,
y : 1337
});

//Cal the methods on those different ways.
$('p').myPlugin('someOtherMethod');
<p class="group-1">group 1</p>
<p class="group-1">group 1</p>
<p class="group-2">group 2</p>
<p class="group-2">group 2</p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

A template for a jQuery plugin with options and accessible methods?

An alternative:

var Plugin = function($self, options) {
this.$self = $self;
this.options = $.extend({}, $.fn.plugin.defaults, options);
};

Plugin.prototype.display = function(){
console.debug("Plugin.display");
};

Plugin.prototype.update = function() {
console.debug("Plugin.update");
};

$.fn.plugin = function(option) {
var options = typeof option == "object" && option;

return this.each(function() {
var $this = $(this);
var $plugin = $this.data("plugin");

if(!$plugin) {
$plugin = new Plugin($this, options);
$this.data("plugin", $plugin);
}

if (typeof option == 'string') {
$plugin[option]();
} else {
$plugin.display();
}
});
};

$.fn.plugin.defaults = {
propname: "propdefault"
};

Usage:

$("span").plugin({
propname: "propvalue"
});

$("span").plugin("update");

This absurdly resembles the Twitter Bootstrap's JavaScript template. But, it wasn't completely taking from there. I have a long history of using .data().

Don't forget to wrap it appropriately.



Related Topics



Leave a reply



Submit