jQuery plugin return this.each - javascript

I am bulding a plugin let's call it ptest and I want to be able to call it with:
$(".myClassName").ptest();
Since I am using attributes from the element on which the plugin is called, lets say data-attribute I now know that returning this.each(...); is a must.
Here is my code:
(function($){
var op;
$.fn.ptest = function(options) {
op = $.extend({
target: null,
attribute: null
}, options);
return this.each(function(){
op.target = $(this);
op.attribute = op.target.attr("data-attribute");
bind();
});
};
function bind(){
op.target.find('.clickable').bind('click',log);
}
function log(){
console.log(op.attribute);
}
}(jQuery));
I know that by having op as a global variable it will always retain the last value for the attribute and the target. How can I make the op variable retain the correct value for each element of .myClassName while being able to access each op from log or bind functions?
I sense i need to declare the functions and the variable in a different way, but how?
I have looked at a lot of different questions and tutorials, here are some:
http://devheart.org/articles/tutorial-creating-a-jquery-plugin/
jQuery plugin development - return this.each issue
jQuery Plugin Return this.each and add function property to each object?
https://learn.jquery.com/plugins/ (of course)

If bind and log really need access to the specific element in the loop, then you need to define them within the each callback, and make op local to that callback:
(function($){
$.fn.ptest = function(options) {
return this.each(function(){
var op = $.extend({
target: $(this)
}, options);
op.attribute = op.target.attr("data-attribute");
bind();
function bind(){
op.target.find('.clickable').bind('click',log);
}
function log(){
console.log(op.attribute);
}
});
};
}(jQuery));
But depending on how you're using bind and log, there may be other options available.

Related

How to reference a function defined inside prototype

I am trying to add a functionality to a web page that uses a jquery library which doesn't seem to have any documentation. (unknown origin) my problem is mainly due to the lack of understanding on jquery plugin model and/or inner workings of javascript.
1. the plugin is initiated as follows
jQuery('div.carousel').scrollGallery({
mask: 'div.mask',
slider: 'div.slideset',
slides: 'div.slide', ............ });
2. the plugin is defined in jquery as follows
;(function($){
function ScrollGallery(options) {
this.options = $.extend({
mask: 'div.mask', ...... }, options);
this.init();
3. in the Object.prototype declaration i see the following function numSlide defined.
ScrollGallery.prototype = {
....................
numSlide: function(c) {
if(this.currentStep != c) {
this.currentStep = c;
this.switchSlide();
}
},
.......... };
Question.
How do i reference numSlide(int) function externally?.
I tried the following methods and it did not work.
myx = jQuery('div.carousel').scrollGallery({ // var myx was added in the global scope
myx.numSlide(1); //error undefined is not a function
i tried adding return this; at the end of myx = jQuery('div.carousel').scrollGallery({ but it still returns the jQuery object.
i also tried
jQuery.scrollGallery().numSlide(2); //error undefined is not a function
jQuery.scrollGallery.numSlide(2); //same error
Do i need to add LIGHT BULB
// jquery plugin
$.fn.scrollGallery = function(opt){
return this.each(function(){
$(this).data('ScrollGallery', new ScrollGallery($.extend(opt,{holder:this})));
});
};
}(jQuery));
ANSWER (I think)
it looks like the ScrollGalary object is stored in a data for the selector. So i believe i can do the following jQuery('selector').data('ScrollGallery').numSlide(2);
I decided to post this anyway in-case if anyone in the future had a similar gullible situation.
One way of doing this will be to initiate ScrollGallery object first and then use it.
var test = new ScrollGallery();
test.numSlide();
if you want to extend jQuery and use the function you can assign it as follows
$.fn.scrollGallery = new ScrollGallery();
and use it
$("window").scrollGallery.numSlide();

jQuery plugin instance variables

I'm beginning with jQuery plugins, apologies for the newbie question. My objective is to have a single plugin instantiated twice, where each instance has its own variables values. However, they seem to share the namespace.
For example, given the following plugin:
(function ( $ ) {
var x = false;
$.fn.test = function() {
alert(x);
if ( !x )
x = true;
return this;
};
}( jQuery ));
that is invoked from the following divs:
$( "div1" ).test();
$( "div2" ).test();
The alert displays first false, then true, when the objective is to have to sets of variables where the alert would display false twice.
is this possible?
There is some confusion in your question. Your plugin is a simple function. You don't "instantiate" a function by calling it. So you don't "instantiate" your plugin either.
You can instantiate things in your function, and persist them somewhere.
Since the outer scope runs only once, in your original solution you only get one instance of variable x.
If you create it inside the function, a new instance gets created every time you call it.
I assume you want to create an instance for every element you call this plugin on. A good solution would be to attach your data to the DOM element you initiate your plugin on, like:
(function ( $ ) {
$.fn.test = function() {
var vars = this.data('testPlugin');
if (!vars) {
vars = {
x: false,
something: 'else'
};
this.data('testPlugin', vars);
}
alert(vars.x);
vars.x = !vars.x;
return this;
};
}( jQuery ));
Try this fiddle.
You should put
var x = false;
inside $.fn.test function, otherwise the x variable is the same for all test() functions, and set to true after first call.
You can read more here about javascript variable scoping.
Actually, this is much easier than the previous answers. The context of this in your plugin is the jQuery object for the DOM element you're receiving based on the selector you provided. To gain uniqueness, simply iterate over each element, like so:
(function($) {
$.fn.test = function() {
return this.each(function() {
var x = false;
alert(x);
if (!x) {
x = true;
}
});
}
}(jQuery));
$("div1").test(); //false
$("div2").test(); // false
Here's a JSFiddle to confirm: http://jsfiddle.net/Z6j7f/

Is it a good practice to store jquery plugin configuration in data?

I want to create jQuery plugin with config (for example plugin myplugin).
Than call $(elem).myplugin(config); After that I want to call methods from this plugin like $(elem).myplugin().method() with already stored config.
My offer is something like that:
(function($) {
$.fn.myplugin = function(options) {
var $this = $(this);
var getOptions = function() {
return $this.data('myplugin');
};
var initOptions = function(opt) {
$this.data('myplugin', opt);
};
var setOption = function(key, value) {
$this.data('myplugin')[key] = value;
}
var updateBorderWidth = function() {
$this.css('border-width',
getOptions().borderWidth * getOptions().coeficient);
};
var init = function(opt) {
initOptions(opt);
updateBorderWidth();
}
function changeBorder(width) {
setOption('borderWidth', width)
updateBorderWidth();
}
if(options) {
init(options);
}
return {
changeBorder : changeBorder
};
}
})(jQuery);
And usage:
$(function() {
var item1 = $('#test1').myplugin({ coeficient: 1, borderWidth: 1 });
var item1 = $('#test2').myplugin({ coeficient: 2, borderWidth: 1 });
$('#btn').click(updateBorder);
});
function updateBorder() {
$('#test1').myplugin().changeBorder($('#inpt').val());
$('#test2').myplugin().changeBorder($('#inpt').val());
}
Example: http://jsfiddle.net/inser/zQumX/4/
My question: is it a good practice to do that?
May be it's incorrect approach. Can you offer better solution?
Edit:
After searching for threads on jQuery plugin template I found these Boilerplate templates (updated) which are more versatile and extensive designs than what I've offered below. Ultimately what you choose all depends on what your needs are. The Boilerplate templates cover more use cases than my offering, but each has its own benefits and caveats depending on the requirements.
Typically jQuery plugins either return a jQuery object when a value is passed to them as in:
.wrap(html) // returns a jQuery object
or they return a value when no parameter is passed in
.width() // returns a value
.height() // also returns a value
To read your example calling convention:
$('#test1').myplugin().changeBorder($('#inpt').val());
it would appear, to any developer who uses jQuery, as though two separate plugins are being utilized in tandem, first .myplugin() which one would assume will return a jQuery object with some default DOM maniplulation performed on #test1, then followed by .changeBorder($('#inpt').val()) which may also return a jQuery object but in the case of your example the whole line is not assigned to a variable so any return value is not used - again it looks like a DOM manipulation. But your design does not follow the standard calling convention that I've described, so there may be some confusion to anyone looking at your code as to what it actually does if they are not familiar with your plugin.
I have, in the past, considered a similar problem and use case to the one you are describing and I like the idea of having a convenient convention for calling separate functions associated with a plugin. The choice is totally up to you - it is your plugin and you will need to decide based on who will be using it, but the way that I have settled on is to simply pass the name of the function and it's parameters either as a separate .myplugin(name, parameters) or in an object as .myplugin(object).
I typically do it like so:
(function($) {
$.fn.myplugin = function(fn, o) { // both fn and o are [optional]
return this.each(function(){ // each() allows you to keep internal data separate for each DOM object that's being manipulated in case the jQuery object (from the original selector that generated this jQuery) is being referenced for later use
var $this = $(this); // in case $this is referenced in the short cuts
// short cut methods
if(fn==="method1") {
if ($this.data("method1")) // if not initialized method invocation fails
$this.data("method1")() // the () invokes the method passing user options
} else if(fn==="method2") {
if ($this.data("method2"))
$this.data("method2")()
} else if(fn==="method3") {
if ($this.data("method3"))
$this.data("method3")(o) // passing the user options to the method
} else if(fn==="destroy") {
if ($this.data("destroy"))
$this.data("destroy")()
}
// continue with initial configuration
var _data1,
_data2,
_default = { // contains all default parameters for any functions that may be called
param1: "value #1",
param2: "value #2",
},
_options = {
param1: (o===undefined) ? _default.param1 : (o.param1===undefined) ? _default.param1 : o.param1,
param2: (o===undefined) ? _default.param2 : (o.param2===undefined) ? _default.param2 : o.param2,
}
method1 = function(){
// do something that requires no parameters
return;
},
method2 = function(){
// do some other thing that requires no parameters
return;
},
method3 = function(){
// does something with param1
// _options can be reset from the user options parameter - (o) - from within any of these methods as is done above
return;
},
initialize = function(){
// may or may not use data1, data2, param1 and param2
$this
.data("method1", method1)
.data("method2", method2)
.data("method3", method3)
.data("destroy", destroy);
},
destroy = function(){
// be sure to unbind any events that were bound in initialize(), then:
$this
.removeData("method1", method1)
.removeData("method2", method2)
.removeData("method3", method3)
.removeData("destroy", destroy);
}
initialize();
}) // end of each()
} // end of function
})(jQuery);
And the usage:
var $test = $('#test').myplugin(false, {param1: 'first value', param2: 'second value'}); // initializes the object
$test.myplugin('method3', {param1: 'some new value', param2: 'second new value'}); // change some values (method invocation with params)
or you could just say:
$('#test').myplugin(); // assume defaults and initialize the selector
Passing parameters to javascript via data attributes is a great pattern, as it effectively decouples the Javascript code and the server-side code. It also does not have a negative effect on the testability of the Javascript code, which is a side-effect of a lot of other approaches to the problem.
I'd go as far as to say it is the best way for server-side code to communicate with client-side code in a web application.

Redefining a jQuery function

I need to redefine the jQuery val() function, but I don't want to mess with the source code. Is it possible to modify it on just one element?
Specifically, I need to do something like this:$("div.smth").val = function() {return this.innerText;};. However, the val function is not modified by this code. What am I doing wrong?
You should instead modify the function of the prototype (jQuery calls this fn). This is where all functions like $(...).something inherit from.
$.fn.val = function() { ... };
If you want to save the original function:
var old = $.fn.val; // `old` won't be overwritten
$.fn.val = function() { ... };
This will do what you want, you need to attach your new val method to jQuery's plugin stack:
$.fn.val = function(value) {
return this[0].innerText;
}
The other answers indicate how to replace the .val() method, but if you know you only need this for one specific element can't you just do this:
$("div.smth")[0].innerText
But in any case isn't that pretty much what the existing jQuery .text() method does?
jsval: function(fn) {
var that = this;
var newfn = function(event) { fn.apply(that, arguments); };
this.click(newfn);
return newfn;
}
Instead now you can call your normal val and on that specific div, call jsval

jQuery Plugin Authoring - Set different options for different elements

I have created a jQuery plugin that works great with the exception of being able to call the plugin on different objects and each object retaining the options it was given. The problem is that if I call the plugin on one object, say:
$('#myDiv1').myPlugin({
option1: 'some text',
option2: true,
option3: 'another option value'
});
then call the plugin again on another object, say:
$('#myDiv2').myPlugin({
option1: 'different text',
option2: false,
option3: 'value for myDiv2'
});
Then if I go back and try to do something with #myDiv1 that needs its original options to still be intact, ie:
$('#myDiv1').myPlugin.update();
it won't have it's original options, but they will be overridden by the options for #myDiv2. What's the proper way to do this so that each object will retain the original options given to it? (And here's some example code of what I'm doing in the plugin)
(function($) {
$.fn.myPlugin = function(options) {
// build main options before element iteration
var opts = $.extend({}, $.fn.myPlugin.defaults, options);
_option1 = opts.option1;
_option2 = opts.option2;
_option3 = opts.option3;
// iterate all matched elements
return this.each(function() {
callPluginFunctions( this, opts );
});
};
....code continued....
I realize this is some kind of scope creep or something. So, how do I get my options to stay attached and remain in the scope of the original object (ie #myDiv1) that they were given to.
EDIT: In doing some research I see that you can store data to an object using jQuery's .data function, and the docs say jQuery UI uses it extensively. Would the proper thing to do here be store the options on the object using .data, then when referenced later use the options stored in .data ???
First, you will generally want to handle the command within your extension method. Second, you should be attaching configurations to each item...
(function($){
var defaultOptions = { /* default settings here */ };
//called on the native object directly, wrap with $(obj) if needed.
function initializeObject(obj, options) {
//assign the options to the object instance.
$(obj).data('myPlugin-options', $.extend(defaultOptions, options) );
//do other initialization tasks on the individual item here...
}
function updateObject(obj) {
// use $(obj).data('myPlugin-options');
}
function setOption(obj, key, value) {
var d = $(obj).data('myPlugin-options');
d[key] = value;
$(obj).data('myPlugin-options', d);
}
$.fn.myPlugin = function(command, option, val) {
if (typeof command == "object") {
//initialization
return this.each(function(){
initializeObject(this, command);
});
}
if (typeof command == "string") {
// method or argument query
switch (command.toLowerCase()) {
case 'option':
//get value, return the first item's value
if (typeof val == undefined) return this.eq(0).data('myPlugin-options')[option];
//set option value
return this.each(function() {
setOption(this, option, val);
});
case 'update':
return this.each(function() {
updateObject(this);
});
//other commands here.
}
}
}
})(jQuery)
With the above example, you have a generic template for a jQuery extension, It's usually good form to have the following convention for use..
Initialization:
$(...).myPlugin({ initialization-options-here });
Command:
$(...).myPlugin('command-name'); //where command can be update, etc.
Get Option:
var myValue = $(...).myPlugin('option', 'option-name');
Set Option:
$(...).myPlugin('option', 'option-name', newValue);
Updated to use .data off of each individual obj.
I've been having the same problem, but only functions passed were being overwritten. Straight up properties were persisting.
Anyway, to further explain what ~reinierpost meant, changing your code to this should work. You'll have to pass 'opts' everywhere, but I think that's necessary to take the options out of the plugin-wide namespace.
$.fn.myPlugin = function(options) {
// iterate all matched elements
return this.each(function() {
// build main options before element iteration
var opts = $.extend({}, $.fn.myPlugin.defaults, options);
callPluginFunctions( this, opts );
});
};
Edit: Here's code from my plugin
this.each(function() {
var thisConfig = config;
thisConfig = $.extend(thisConfig,settings);
$.attach($(this),thisConfig);
});
...
$.attach = function($target,config){
So I have no plugin-wide "config" - just inside each function.
Your options are plugin-wide. Move them inside the each().
(Why are you asking this question? You pretty much spell out the solution yourself.)

Categories