append method to jquery plugin - javascript

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');
}
}
});
});

Related

jQuery plugin - update settings after initialization

I have a jQuery plugin, and I want to be able to change options on the fly, like this example: $('.element').pwstabs('options','effect',scale) or something simular to it. I tried adding update: function, tried adding Plugin.prototype.update, but still cant figure out how to do that :)
Here's the structure of the plugin:
;(function ($, window, document, undefined) {
var pluginName = "pwstabs",
defaults = {
effect: 'scaleout',
defaultTab: 1,
containerWidth: '100%',
tabsPosition: 'horizontal',
horizontalPosition: 'top',
verticalPosition: 'left',
responsive: false,
theme: '',
rtl: false,
controlls: false,
next: '',
prev: '',
first: '',
last: '',
auto: false,
play: '',
pause: ''
};
function Plugin(element, options) {
this.element = $(element);
this.$elem = $(this.element);
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function(){
// Here's the code for the plugin
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
new Plugin( this, options );
});
};
})(jQuery, window, document);
So now I use the plugin like:
$('.element').pwstabs({
effect: 'scalein',
defaultTab: 2
});
And when I click a button, i want to change effect to lets say scaleout. With code like:
$('.button').click(function(){
$('.element').pwstabs('options','effect','scalein');
});
So how do I implement this in the plugin?
Currently the only supported invocation pattern in that plugin is to send in an object literal containing the settings to overwrite the defaults. E.g.:
$('.element').pwstabs({
effect: 'scalein',
defaultTab: 2
});
That invocation pattern is defined in the following method:
$.fn[pluginName] = function ( options ) {
return this.each(function () {
new Plugin( this, options );
});
};
As you see, a dictionary of options is sent as the only parameter to the constructor function Plugin() to build the plugin and initialize it.
To support the invocation pattern you need, you would have to modify this method to support both invocation patterns (initialization with an object literal, but also invoking any method with more params, like your options setting method).
Here is an improved function that will handle both invocation patterns. In addition it will also store the instance of a plugin on an element, so you can access the existing settings etc. on subsequent invocations (e.g. settings changes) on the same element.
$.fn[pluginName] = function (options) {
// get the arguments
var args = $.makeArray(arguments),
after = args.slice(1);
return this.each(function () {
// check if there is an existing instance related to element
var instance = $.data(this, pluginName);
if (instance) {
if (instance[options]) {
instance[options].apply(instance, after);
} else {
$.error('Method ' + options + ' does not exist on Plugin');
}
} else {
// create the plugin
var plugin = new Plugin(this, options);
// Store the plugin instance on the element
$.data(this, pluginName, plugin);
return plugin;
}
});
}
This would allow you to invoke the plugin as requested:
$('.element').pwstabs('options','effect','slidedown');
However, this implies you have an 'options' method in the Plugin prototype, so make sure to add one:
Plugin.prototype = {
options: function (option, val) {
this.settings[option] = val;
},
// Constructing Tabs Plugin
init: function () {
// omitted code for brevity
}
}
As you see the options settings just sets the new option on the existing instance. Very simple and efficient. The new setting will be picked up by the click method handler and voila!
Here is a jsFiddle with example code in case you have trouble implementing what i was describing so far:
http://jsfiddle.net/7whs3u1n/6/
Update: I have much improved my answer to get rid of unneeded stuff, include more details and a full implementation that works (check the fiddle above) ;) i hope that this answers your question!
Adding statefulness to your plugin wasn't hard, but when you have spare time also check the alternative mechanism for writing stateful jQuery stateful plugins called jQuery widget factory:
http://learn.jquery.com/plugins/stateful-plugins-with-widget-factory/
In the future you can consider rewriting your plugin to use the widget factory. It would certainly make your code simpler ;)
Try this pattern
(function ($) {
var defaults = {
"text": "abcdefg",
}
, options = $.extend({}, defaults, options);
$.fn.plugin = function (options) {
var options = (function (opts, def) {
var _opts = {};
if (typeof opts[0] !== "object") {
_opts[opts[0]] = opts[1];
};
return opts.length === 0
? def
: typeof opts[0] === "object"
? opts[0] : _opts
}([].slice.call(arguments), defaults));
return $(this).text(options.text)
}
}(jQuery));
$(".results:eq(0)").plugin(); // return `defaults`
$(".results:eq(1)").plugin({"text":"gfedcba"}); // return `options`
$(".results:eq(2)").plugin("text", 123); // return `arguments` as `options`
(function ($) {
var defaults = {
"text": "abcdefg",
}
, options = $.extend({}, defaults, options);
$.fn.plugin = function (options) {
var options = (function (opts, def) {
var _opts = {};
if (typeof opts[0] !== "object") {
_opts[opts[0]] = opts[1];
};
return opts.length === 0
? def
: typeof opts[0] === "object"
? opts[0] : _opts
}([].slice.call(arguments), defaults));
return $(this).text(options.text)
}
}(jQuery));
$(".results:eq(0)").plugin(); // return `defaults`
$(".results:eq(1)").plugin({"text":"gfedcba"}); // return `options`
$(".results:eq(2)").plugin("text", 123); // return `arguments` as `options`
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="results"></div><br />
<div class="results"></div><br />
<div class="results"></div>

Modify jQuery plugin function externally

I'm working with iThemes Exchange for WordPress and I'm trying to modify the javascript file that controls certain aspects of the iThemes Exchange shopping cart checkout process.
The problem is I can't modify the plugin itself because any changes will be overwritten when the client updates their plugins. So I'm trying to modify the javascript plugin's updateStates() function so that the country label is automatically set to "United States".
I've tried modifying the plugin using jQuery.fn.itCountryStatesSync which is where the plugin is, but I must be doing something wrong. If it helps I'll include the plugin's javascript file.
/**
* jQuery Country States Sync Plugin by iThemes
* Plugin framework via <http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/>
*/
;(function ( $, window, document, undefined ) {
// Create the defaults once
var pluginName = 'itCountryStatesSync',
defaults = {
stateWrapper : '.it-exchange-state',
stateFieldID : '#it-exchange-address-state',
action : 'ite-country-states-update',
templatePart : '',
clearTextValue : false,
ajaxUrl : itExchangeAjaxCountryStatesAjaxURL,
adminPrefix : false,
autoCompleteState : false,
autoFocusState : false
};
// The actual plugin constructor
function Plugin( countrySelectElement, options ) {
// Set element
this.element = countrySelectElement;
// jQuery has an extend method that merges the
// contents of two or more objects, storing the
// result in the first object. The first object
// is generally empty because we don't want to alter
// the default options for future instances of the plugin
this.options = $.extend( {}, defaults, options) ;
// Country Field ID
this.options.countryFieldID = '#' + $(this.element).attr('id');
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function () {
// Place initialization logic here
// You already have access to the DOM element and
// the options via the instance, e.g. this.element
// and this.options
$(this.element).on('change', this.options, this.updateStates );
};
Plugin.prototype.updateStates = function( event ) {
var iteCountryStatesSyncPostData = {};
iteCountryStatesSyncPostData.ite_base_country_ajax = $(event.data.countryFieldID).val();
iteCountryStatesSyncPostData.ite_base_state_ajax = $(event.data.stateFieldID).val();
iteCountryStatesSyncPostData.ite_state_name_ajax = $(event.data.stateFieldID).attr('name');
iteCountryStatesSyncPostData.ite_action_ajax = event.data.action;
iteCountryStatesSyncPostData.ite_template_part_ajax = event.data.templatePart;
iteCountryStatesSyncPostData.ite_admin_prefix_ajax = event.data.adminPrefix;
iteCountryStatesSyncPostData.ite_clearTextValue = event.data.clearTextValue;
$.post(event.data.ajaxUrl, iteCountryStatesSyncPostData, function(response) {
if (response) {
var parentForm = $(event.data.countryFieldID).closest('form');
$(event.data.stateWrapper, parentForm).html(response);
if (event.data.autoCompleteState)
$(event.data.stateFieldID).filter('select').selectToAutocomplete();
if (event.data.autoFocusState) {
if ( $(event.data.stateWrapper).children('.ui-autocomplete-input').length !== 0 ) {
$(event.data.stateWrapper).children('.ui-autocomplete-input').focus();
} else {
$(event.data.stateFieldID).focus();
}
}
}
});
}
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin( this, options ));
}
});
}
})( jQuery, window, document );

How to call elements inside user defined methods of an jQuery plugin

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

Method for jQuery plugin

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'});

jQuery .data() and plugins

I am trying to use jQuery's .data() tool in a jQuery plugin but I'm getting some odd results.
Here is a cut down version of my plugin with the relevant code:
(function( $ ){
var methods = {
init : function( options ) {
// Do some stuff
this.data('name', 'New Component');
return this;
},
getStateData : function () {
// Function returns all data for save
var state = new Object;
state.name = this.data('name');
// snip ... Add some other bits to state
// ...
return state;
},
setStateData: function (args) {
var key = args[0];
var value = args[1];
// snip
this.data(key, value);
}
};
$.fn.component7Segment = 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.designComponent' );
}
};
})( jQuery );
If I call $(instance-of-plugin).component7Segment('getStateData'); the plugin returns the correct 'name' however if I call setStateData to change the name it has not changed the 'name' value when I next call getStateData.
Doing console.log(this); in each function looks slightly different so I started trying:
$.data($('#object-id'), 'name', value);
This still doesn't have the desired effect.
Can anybody see what I am missing?
Assuming you're calling setStateData like this:
$(instance).component7Segment("setStateData", "name", "Foo");
the setStateData function should be changed to look like this:
setStateData: function () {
var key = arguments[0];
var value = arguments[1];
// snip
this.data(key, value);
}
Note the removal of the args parameter and the use of the special arguments array-like object instead.
Example: http://jsfiddle.net/andrewwhitaker/ShFHC/
Your original problem was most likely that you were calling setStateData with parameters name and "foo". args[0] and args[1] was actually accessing the characters in name at that position instead of the arguments passed to the function.

Categories