I have a jQuery Plugin which accept multiple elements and some methods to be called like:
(function($){
methods = {
init : function( options, callbacks) {
$.fn.myPlugin.settings = $.extend({
'userDefinedMethod': function() {}
}, options);
return this.each(function(){
$.fn.myPlugin.settings.userDefinedMethod();
}
}
}
$.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 exists on jQuery.myPlugin' );
}
}
})(jQuery);
An simple example which will make you understand what I want to achieve:
$(document).ready(function(){
$('#myElement1, #myElement2, #myElement3').myPlugin({
userDefinedMethod: function() {
// I want here to use the elements in selector
$(this).css('color', 'black');
}
});
});
I know that $(this) in the example above will represent the jQuery Plugin Object but I want somehow to use each element in the provided selector.
$(document).ready(function () {
$('#myElement1, #myElement2, #myElement3').myPlugin({
userDefinedMethod: function () {
// I want here to use the elements in selector
$(this).css('color', 'red');
}
});
});
(function ($) {
methods = {
init: function (options, callbacks) {
//don't set the settings to shared object
this.settings = $.extend({
userDefinedMethod: $.noop
}, options);
return this.each($.proxy(function (idx, el) {
//use Function.call() to set a custom execution context
this.settings.userDefinedMethod.call(el);
}, 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 exists on jQuery.myPlugin');
}
}
})(jQuery);
Demo: Fiddle
In methods.init function this will be the jQuery object obtained by quering the selector. So, if you want to send this to userDefinedMethod just use apply or call when you call that function:
...
var methods = {
init : function( options, callbacks) {
$.fn.myPlugin.settings = $.extend({
'userDefinedMethod': function() {}
}, options);
$.fn.myPlugin.settings.userDefinedMethod.call(this);
// or if you want to send the arguments
// $.fn.myPlugin.settings.userDefinedMethod.apply(this, arguments);
return this;
}
}
...
Also, don't forget that you didn't use var for declaring methods. methods will become a magic global variable...
I also corrected the missing ) that was generating a syntax error.
JSFIDDLE
Related
i write this plugin and now i want add method to this plugin such as this
$.createMessage().removeMessage()
how can i do it?
my code is
$(function () {
$.extend({
createtext: function (options) {
var setting = {
holder: "",
text: "",
}
if (options != null) {
$.extend(setting, options)
}
var $this = $(setting.holder)
$this.find("div#CreatetextHolder").remove()
$this.append("<div id='CreatetextHolder'><span></span><p class='Createtext'>" + setting.text + "</p></div>")
$this.find("div#CreatetextHolder").fadeIn('slow')
}
})
})
thank you for your help
$(selector).createMessage().removeMessage() would require you to write two plugins - one for 'create' and the other for 'remove'.
It's far better to do everything in one plugin and you can do so by targeting the syntax ...
$(selector).createMessage('remove');
Then it's a matter of testing options in the plugin code, and branching accordingly.
Currently you test if (options != null) assuming options to be a javascript plain object and that the only action is initianisation.
But with my suggestion to allow $.createMessage('remove'), you need to perform more extensive testing/branching depending on what parameter(s) are actually passed.
For example:
$(function () {
$.extend({
createtext: function ( method, options ) {
var settings = {
holder: "",
text: ""
};
var methods = {
'init': function(options) {
var _settings = $.extend({}, settings, options);//this leaves `settings` unaffected and available for reuse in future inits.
//initialize here
},
'remove': function() {
//uninitialize here
}
}
// These tests allow `init' to be passed explicitly,
// or assumed if an options object is the only argument.
// Otherwise, a method such as 'remove' may be passed,
// with or without further parameters.
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 in jQuery.createtext');
}
}
});
});
I'm trying to write a simple jQuery plugin that follows similar structure to the one below. The problem I'm having is that when I initialize the plugin the value plugin.myValue is set to 1 however when I try to access that value in the talk function it's undefined. Can anyone help me refine this plugin structure so when I set values on the plugin object they can be accessed in different methods.
Please keep in mind that the plugin below is not my actual use case it is just a simple example to illustrate the problem I'm having.
My actual use case would be very long because it is a jQuery carousel that I'm writing. If it will help I can provide that code however it's much longer and the below example follows the same flow. I would initialize this plugin with the following code:
$('#Div1').talk({ message: "test message" });
$('#Div1').talk('talk');
(function ($) {
$.fn.talk = function(method) {
var settings = {};
var $el = $(this);
var plugin = this;
var methods = {
init: function(options){
settings = $.extend(true, settings, this.talk.defaults, options);
return this.each(function() {
plugin.myValue = 1;
});
},
talk: function(){
helpers.talk(settings.message);
}
}
var helpers = {
talk: function(message){
if (plugin.myValue == 1)
{
alert(message);
}
}
}
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 in talk plugin!');
}
}
$.fn.talk.defaults = {
message: "default message"
}
})(jQuery);
When you define a plugin, this refers already to the jquery object (not the dom element), so I think your plugin var should go en each element, like this:
(function ($) {
$.fn.talk = function(method) {
var settings = {};
var $el = this; //Not need of $() here
var methods = {
init: function(options){
settings = $.extend(true, settings, this.talk.defaults, options);
return this.each(function(index, item) {
item.myValue = 1; //check this
});
},
talk: function(){
helpers.talk.call(this, settings.message); //talk needs scope
}
}
var helpers = {
talk: function(message){
var $elems = this;
if ($elems[0] && $elems[0].myValue == 1) //Something like this
{
alert(message);
}
}
}
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 in talk plugin!');
}
}
$.fn.talk.defaults = {
message: "default message"
}
})(jQuery);
I hope you get my idea. Don't forget that your selector might match to more than one element. You were stroring the data to the jquery object, and don't forget that it's a different one each time you call $("#yourDiv"), so your data was lost.
Note: It'd be cleaner to do $(item).data('myValue', 1); instead of item.myValue = 1; (and its proper retrieval), but it's a matter of choice
EDIT Option 2. This may look more similar to your code, but will work only when your selector only matched a single element
(function ($) {
$.fn.talk = function(method) {
var settings = {};
var $el = this; //Not need of $() here
var methods = {
init: function(options){
settings = $.extend(true, settings, this.talk.defaults, options);
$el.data("myValue", 1);
},
talk: function(){
helpers.talk(settings.message);
}
}
var helpers = {
talk: function(message){
if ($el.data("myValue") == 1)
{
alert(message);
}
}
}
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 in talk plugin!');
}
}
$.fn.talk.defaults = {
message: "default message"
}
})(jQuery);
Hope this helps. Cheers
I have a basic plugin that populates an array within the plugin. How can I get that array via a method call with parameters. This is my first plugin so please go easy on me if this is a dumb question.
basic Plugin
(function($) {
$.fn.myPlugin = function() {
return this.each(function(){
tagArray = []; // my array that is populated
//code that does stuff to populate array
});
}
})(jQuery);
I would like to get the tagArray like so...
var arr = $('.className').myPlugin("getArray");
Where I can then use that array elsewhere. How can I accomplish this?
Thank you for any help.
I don't see why you would need the "getArray" parameter. In any case you need to define only 1 array and make your function return it:
(function($) {
$.fn.myPlugin = function() {
var tagArray = [];
this.each(function(){
// add something to tagArray
});
return tagArray;
}
})(jQuery);
That's a rather strange requirement, but an easy way to do that if there is only parameter would be something like :
(function($) {
$.fn.myPlugin = function(param) {
var tagArray = [],
elems = this.each(function(){
tagArray.push( $(this).text() ); // whatever you do ??
});
return param == 'getArray' ? tagArray : elems;
} // ^^ if the parameter is passed, return the array, otherwise the elems
})(jQuery);
FIDDLE
It's a bit hackish, but it works. You could also just return this.map(function() {... to always return an array etc, or read up on how to pass multiple parameters to a plugin and do different things etc. instead of the hardcoded check for 'getArray' used above.
Try
(function($) {
function Plugin($el, opts){
this.tagArray = [];
this.tagArray.push($el.attr('id')) //for testing the retuned instance
$el.data('myPlugin', this);
}
Plugin.prototype.getTagArray = function(){
return this.tagArray;
}
$.fn.myPlugin = function(opts) {
if($.type(opts) == 'string'){
var plugin = this.data('myPlugin');
return plugin[opts]();
}
return this.each(function(){
var $this = $(this);
new Plugin($this);
});
}
})(jQuery);
jQuery(function(){
$('#e1, #e2, #e3').myPlugin();
console.log($('#e1').myPlugin('getTagArray'))
console.log($('#e2').myPlugin('getTagArray'))
console.log($('#e3, #e1').myPlugin('getTagArray'))
})
Demo: Fiddle
I just finished writing a JQuery Plugin myself and here is the basic structure I settled on:
(function (window, document, $, undefined) {
//Local Methods
var methods = {
init : function(options){
//stuff you want to do when your plugin initializes i.e. when you do $('selector').myPlugin(options)
},
getArray: function(){
//your getArray method. Put your get array logic here
}
}
//Plugin Initialize
$.fn.myPlugin = function(args){
if ( methods[args] )
{
//execute JQuery Plugin Method
return methods[ args ].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
else if ( typeof args === 'object' || ! args )
{
//Process JQuery Plugin Options
var opts = $.extend({}, $.fn.myPlugin.defaults, args);
var new_args = new Array(opts);
return methods.init.apply( this, new_args );
}
else
{
$.error( 'Method ' + args + ' does not exist on myPlugin' );
}
};
//Define Default Options
$.fn.myPlugin.defaults = {
option_1: '',
option_2: '',
option_n: ''
}
//API Methods
var M = $.myPlugin = function(){};
$.extend(M, {
getArray: function(){
return methods.getArray();
}
});
}(window, document, jQuery));
Doing this allows you to start your plugin like this (as usual):
$('.className').myPlugin(options);
and/or call your getArray function like this:
$.myPlugin.getArray();
I hope this helps you get closer to where you want to be.
I'm trying to make a jQuery plugin for custom checkboxes and radio buttons.
(function($)
{
$.fn.checkboxRadio = function(options)
{
var defaults = some;
...
return this.each(function()
{
var button = $(this);
...
});
}
})(jQuery);
It can be used now by $('input').checkboxRadio(options);
How do I add a method check without changing current scope, to make a possible usage of something like $('input').checkboxRadio('check')?
How to handle a custom method and get its name inside my plugin?
Here is the official jquery plugin guide.
The part about wrapping functions is found here ("Plugin Methods") (the example is a would-be tooltip plugin) :
(function( $ ){
var methods = {
init : function(options) { ... },
show : function() { ... },
hide : function() { ... },
update : function(content) { ... }
};
$.fn.tooltip = function( method ) {
// Method calling logic
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.tooltip' );
}
};
})(jQuery);
[update] explaining the methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )) line in the guide :
If you call $(selector).tooltip('update', 'hello') from your javascript code, you want to end up calling the update method, passing 'hello' as the content argument, with this set to $(selector) for the duration of the call.
That is what this line takes care of :
if method == 'update', methods[method] is the update method,
arguments will be equal to ['update', 'hello'], you have to drop the first element to get the arguments you want to pass to your method ; this is exactly what Array.prototype.slice.call(arguments, 1) does,
myFunc.apply(obj, argsArray) calls the function myFunc, passing argsArray as the arguments, and setting this to obj for the duration of the call.
So inside your methods, you can call this.each(...) to iterate over all of the selector's items, e.g. :
update: function(content) {
this.each(function(){ $(this).data('tooltip.content', content); });
return this;
}
You can connect plugin methods like this:
(function($) {
$.fn.checkboxRadio = function(options) {
var defaults = {
check: 'check'
}
return this.each(function() {
var o = options;
var _this = $(this);
if( o.check === 'check' ) {
_this.attr('checked','checked');
}else if ( o.check === 'uncheck' ) {
_this.removeAttr('checked');
}
});
}
})(jQuery);
and user document should be like what you want: $('input').checkboxRadio({check:'check'});
I'm working on a jquery plug in and I'm running into a problem saving properties for later use. In the example below, the console output is 18, 50, 50 when I'm looking for 18, 50, 18. I understand why this is happening, but I can't figure out a good way to save properties for use in multiple different methods. I have a feeling I'm missing something very obvious, but I'm just not seeing it.
<html>
<body>
<h1>Hello</h1>
<h2>World</h2>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript">
(function ($) {
var commonOperations, methods, properties;
commonOperations = function () {
console.log(properties.height);
};
methods = {
init : function (overrides) {
var defaults;
defaults = { height: 18 };
properties = $.extend(defaults, overrides);
commonOperations();
},
foo : function () {
commonOperations();
}
};
$.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 for jQuery.myPlugin');
}
};
}(jQuery));
$(document).ready(function () {
$("h1").myPlugin();
$("h2").myPlugin({ height: 50 });
$("h1").myPlugin("foo");
});
</script>
</body>
</html>
It depends on the nature of your plugin, but it's likely that using .data() to store the properties on a per-element basis would make sense.
init: function(overrides) {
return this.each(function() {
var defaults = { whatever: "foo" };
$(this).data('properties', $.extend(defaults, overrides));
});
}
Then the other methods always pull the "properties" object from the element:
foo : function () {
return this.each(function() {
commonOperations.call(this, $(this).data('properties'));
});
}