Here is a fictional version of my jQuery plugin, but the structure is exactly the same:
(function ($)
{
var initialized = false;
var element;
var counter = 0;
$.fn.myPlugin= function(action)
{
if (action === "increase")
{
increase(arguments[1]);
}
else if (!initialized)
{
settings = $.extend({
...
}, action);
initialized = true;
element = $(this);
return this;
}
else
{
console.error("Unknown function call.");
return;
}
};
var increase = function(amount)
{
counter += amount;
element.text(counter);
};
}(jQuery));
With this code I am able to initialize my plugin like this:
$("#element").myPlugin(options);
And I can call the method increase like this:
$("#element").myPlugin("increase", 5);
However, I am not able to initialize my plugin on multiple elements on one page, because of the variables initilized, element and counter.
How do I modify this code in such a way that I can use it multiple times on one page without changing the way you can initialize and call methods?
I do this exact same thing myself, and it's very simple once you know how.
Take this example of a simple plugin...
$.fn.myPlugin = function() {
// plugin global vars go here
// do plugin stuff here
}
To modify it to work on multiple instances, you just have to parse this when you call it...
$.fn.myPlugin = function() {
$(this).each(function() {
// plugin global vars go here
// do plugin stuff here
});
}
That way it will work when you assign the plugin to either a single instance, or a collection of elements.
Then, to call methods on individual elements, you just need to specify the correct one...
$("#element1").doMethod(1, 2, 3);
$("#element2").doMethod(4, 5, 6);
Related
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.
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.
i have this countdown timer
(function($){
var options = {
display_as_text : false,
remaining : 0,
separator : ':',
significant_days : 3,
display_on_complete : null, // id of element to display when countdown is complete
hide_on_complete : null // hide the timer once it hits zero
};
$.fn.countdown = function (config_options)
{
/*
* Initialise
*
* Prepare data and trigger regular execution of code
*
* #param container Reference to DOM element where counter will be displayed
*/
var initialise = function (container){
}
var update = function (seconds_remaining){
}
and i need to access the update and reset the time based on a value i send in but i dont know how to access it. Here is how i instantiate the plugin
$('#timer').countdown({remaining : 1000});
but how do i call the update to update the seconds...I tried to set it to a variable and call it but no go...any ideas
The most common approach (that I've seen) is to do things jQuery-UI style:
$(selector).plugin({...}) binds the plugin and allows chaining in the usual fashion.
$(selector).plugin('method') calls method as an accessor.
$(selector).plugin('method', arg) calls method as a mutator with the specified arg.
So in your case, you'd want to add a bit of argument parsing logic to your plugin so that you could say things like $(selector).countdown('update', 11).
You can use $.isPlainObject and arguments to figure out how the plugin was called and pull apart the variable length argument list:
$.fn.countdown = function(options) {
if(!$.isPlainObject(options)) {
var stdarg = Array.prototype.slice.call(arguments);
if(stdarg[0] == 'update' && stdarg.length > 1) {
return this.each(function() {
// Set up value using stdarg[1]
});
}
// ...
}
return this.each(function() {
// Bind as usual
});
};
And a simple demo (reality would of course be cleaner and better organized): http://jsfiddle.net/ambiguous/DEVBD/
I’m not sure you want to retrieve the seconds remaining or call the update function inside the plugin. But either way It’s impossible to tell if this is included in the plugin without looking at the full source.
You can always add a custom API to the plugin if you manipulate it, using something like this inside the plugin scope:
$(this).data('countdown', {
update: update
});
Then call it using:
$('#timer').data('countdown').update(12345);
The same idea would work for getting internal variables, such as seconds remaining, f.ex: (assuming that the internal variable is called seconds_remaining):
$(this).data('countdown', {
getSecondsRemaining: function() {
return seconds_remaining;
}
});
And then:
$('#timer').data('countdown').getSecondsRemaining();
I have one page with two types of forms. I have a single form of type A at the top, and then I have 1 or more forms of type B below it.
I use the Module pattern + jQuery to wire up all the events on my forms, handle validation, ajax calls, etc.
Is this the preferred/valid way to define a singleton, as in Form A, and a reusable object class, as in Form B? They are very similar and I'm not sure if I need to be using object the prototype property, new, or a different pattern. Everything seems to work for me but I'm afraid I'm missing some key error.
Form A javascript looks like this:
var MyProject.FormA = (function() {
var $_userEntry;
var $_domElementId;
var validate = function() {
if($_userEntry == 0) {
alert('Cannot enter 0!');
}
}
var processUserInput = function() {
$_userEntry = jQuery('inputfield', $_domElementId).val();
validate();
}
return {
initialize: function(domElementId) {
$_domElementId = domElementId;
jQuery($_domElementId).click(function() {
processUserInput();
}
}
}
})();
jQuery(document).ready(function() {
MyProject.FormA.initialize('#form-a');
});
Form B, which is initialized one or many times, is defined like so:
var MyProject.FormB = function() {
var $_userEntry;
var $_domElement;
var validate = function() {
if($_userEntry == 0) {
alert('Cannot enter 0!');
}
}
var processUserInput = function() {
$_userEntry = jQuery('inputfield', $_domElement).val();
validate();
}
return {
initialize: function(domElement) {
$_domElement = domElement;
jQuery($_domElement).click(function() {
processUserInput();
}
}
}
};
jQuery(document).ready(function() {
jQuery(".form-b").each(function() {
MyProject.FormB().initialize(this);
});
});
Both of your modules explicitly return objects which precludes the use of new.
Prototype inheritance isn't really compatible with the method hiding your achieving with this pattern. Sure you could re-write this with a prototype form object with your validate method defined on it, but then this method would be visible and you'd loose the encapsulation.
It's up to you whether you want the low memory footprint and speedy object initialization of prototypes (Shared methods exist only once, Instantiation runs in constant time) or the encapsulation of the module pattern which comes with a slight performance penalty (Multiple defined identical methods, Object instantiation slowed as every method has to be created every time)
In this case I would suggest that the performance difference is insignificant, so pick whatever you like. Personally I would say there is too much duplication between them and I would be inclined to unify them. Do you really need A to be a singleton? What are the dangers of it being accidentally instantiated twice? Seems like this is maybe over-engineering for this problem. If you really must have a singleton I'd wrap the non-singleton (B) class like this:
var getSingleton = function() {
var form = MyProject.FormB();
form.initialize("#form-a");
console.log("This is the original function");
getSingleton = function() {
console.log("this is the replacement function");
return form;
}
return form;
}
I think you just need to write a kind of jQ plugin:
(function($) {
$.fn.formValidator = function() {
return $(this).each(function() {
var $_domElement = $(this);
$_domElement.click(function() {
if($('inputfield', $_domElement).val() == 0) {
alert('Cannot enter 0!');
}
});
});
};
})(jQuery);
In this case you'll extend jQ element methods module and will be able to use it for any amount of elements at the page (for single or multiple elements collection). Also it will be chainable.
Usage:
$('#form-a').formValidator();
$('.form-b').formValidator();
Or
$('#form-a, .form-b').formValidator();
Ofcourse you can use a module to store this function:
ProjectModule.formValidator = function(selector) {
return $(selector).each(function() {
var $_domElement = $(this);
$_domElement.click(function() {
if ($('inputfield', $_domElement).val() == 0) {
alert('Cannot enter 0!');
}
});
});
};
Usage:
ProjectModule.formValidator('#form-a, .form-b');
I edited the question so it would make more sense.
I have a function that needs a couple arguments - let's call it fc(). I am passing that function as an argument through other functions (lets call them fa() and fb()). Each of the functions that fc() passes through add an argument to fc(). How do I pass fc() to each function without having to pass fc()'s arguments separately? Below is how I want it to work.
function fa(fc){
fc.myvar=something
fb(fc)
}
function fb(fc){
fc.myothervar=something
fc()
}
function fc(){
doessomething with myvar and myothervar
}
Below is how I do it now. As I add arguments, it's getting confusing because I have to add them to preceding function(s) as well. fb() and fc() get used elsewhere and I am loosing some flexibility.
function fa(fc){
myvar=something
fb(fc,myvar)
}
function fb(fc,myvar){
myothervar=something
fc(myvar,myothervar)
}
function fc(myvar,myothervar){
doessomething with myvar and myothervar
}
Thanks for your help
Edit 3 - The code
I updated my code using JimmyP's solution. I'd be interested in Jason Bunting's non-hack solution. Remember that each of these functions are also called from other functions and events.
From the HTML page
<input type="text" class="right" dynamicSelect="../selectLists/otherchargetype.aspx,null,calcSalesTax"/>
Set event handlers when section is loaded
function setDynamicSelectElements(oSet) {
/**************************************************************************************
* Sets the event handlers for inputs with dynamic selects
**************************************************************************************/
if (oSet.dynamicSelect) {
var ySelectArgs = oSet.dynamicSelect.split(',');
with (oSet) {
onkeyup = function() { findListItem(this); };
onclick = function() { selectList(ySelectArgs[0], ySelectArgs[1], ySelectArgs[2]) }
}
}
}
onclick event builds list
function selectList(sListName, sQuery, fnFollowing) {
/**************************************************************************************
* Build a dynamic select list and set each of the events for the table elements
**************************************************************************************/
if (fnFollowing) {
fnFollowing = eval(fnFollowing)//sent text function name, eval to a function
configureSelectList.clickEvent = fnFollowing
}
var oDiv = setDiv(sListName, sQuery, 'dynamicSelect', configureSelectList); //create the div in the right place
var oSelected = event.srcElement;
if (oSelected.value) findListItem(oSelected)//highlight the selected item
}
Create the list
function setDiv(sPageName, sQuery, sClassName, fnBeforeAppend) {
/**************************************************************************************
* Creates a div and places a page in it.
**************************************************************************************/
var oSelected = event.srcElement;
var sCursor = oSelected.style.cursor; //remember this for later
var coords = getElementCoords(oSelected);
var iBorder = makeNumeric(getStyle(oSelected, 'border-width'))
var oParent = oSelected.parentNode
if (!oParent.id) oParent.id = sAutoGenIdPrefix + randomNumber()//create an ID
var oDiv = document.getElementById(oParent.id + sWindowIdSuffix)//see if the div already exists
if (!oDiv) {//if not create it and set an id we can use to find it later
oDiv = document.createElement('DIV')
oDiv.id = oParent.id + sWindowIdSuffix//give the child an id so we can reference it later
oSelected.style.cursor = 'wait'//until the thing is loaded
oDiv.className = sClassName
oDiv.style.pixelLeft = coords.x + (iBorder * 2)
oDiv.style.pixelTop = (coords.y + coords.h + (iBorder * 2))
XmlHttpPage(sPageName, oDiv, sQuery)
if (fnBeforeAppend) {
fnBeforeAppend(oDiv)
}
oParent.appendChild(oDiv)
oSelected.style.cursor = ''//until the thing is loaded//once it's loaded, set the cursor back
oDiv.style.cursor = ''
}
return oDiv;
}
Position and size the list
function configureSelectList(oDiv, fnOnClick) {
/**************************************************************************************
* Build a dynamic select list and set each of the events for the table elements
* Created in one place and moved to another so that sizing based on the cell width can
* occur without being affected by stylesheet cascades
**************************************************************************************/
if(!fnOnClick) fnOnClick=configureSelectList.clickEvent
if (!oDiv) oDiv = configureSelectList.Container;
var oTable = getDecendant('TABLE', oDiv)
document.getElementsByTagName('TABLE')[0].rows[0].cells[0].appendChild(oDiv)//append to the doc so we are style free, then move it later
if (oTable) {
for (iRow = 0; iRow < oTable.rows.length; iRow++) {
var oRow = oTable.rows[iRow]
oRow.onmouseover = function() { highlightSelection(this) };
oRow.onmouseout = function() { highlightSelection(this) };
oRow.style.cursor = 'hand';
oRow.onclick = function() { closeSelectList(0); fnOnClick ? fnOnClick() : null };
oRow.cells[0].style.whiteSpace = 'nowrap'
}
} else {
//show some kind of error
}
oDiv.style.width = (oTable.offsetWidth + 20) + "px"; //no horiz scroll bars please
oTable.mouseout = function() { closeSelectList(500) };
if (oDiv.firstChild.offsetHeight < oDiv.offsetHeight) oDiv.style.height = oDiv.firstChild.offsetHeight//make sure the list is not too big for a few of items
}
Okay, so - where to start? :) Here is the partial function to begin with, you will need this (now and in the future, if you spend a lot of time hacking JavaScript):
function partial(func /*, 0..n args */) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
var allArguments = args.concat(Array.prototype.slice.call(arguments));
return func.apply(this, allArguments);
};
}
I see a lot of things about your code that make me cringe, but since I don't have time to really critique it, and you didn't ask for it, I will suggest the following if you want to rid yourself of the hack you are currently using, and a few other things:
The setDynamicSelectElements() function
In this function, you can change this line:
onclick = function() { selectList(ySelectArgs[0], ySelectArgs[1], ySelectArgs[2]) }
To this:
onclick = function() { selectList.apply(null, ySelectArgs); }
The selectList() function
In this function, you can get rid of this code where you are using eval - don't ever use eval unless you have a good reason to do so, it is very risky (go read up on it):
if (fnFollowing) {
fnFollowing = eval(fnFollowing)
configureSelectList.clickEvent = fnFollowing
}
And use this instead:
if(fnFollowing) {
fnFollowing = window[fnFollowing]; //this will find the function in the global scope
}
Then, change this line:
var oDiv = setDiv(sListName, sQuery, 'dynamicSelect', configureSelectList);
To this:
var oDiv = setDiv(sListName, sQuery, 'dynamicSelect', partial(configureSelectListAlternate, fnFollowing));
Now, in that code I provided, I have "configureSelectListAlternate" - that is a function that is the same as "configureSelectList" but has the parameters in the reverse order - if you can reverse the order of the parameters to "configureSelectList" instead, do that, otherwise here is my version:
function configureSelectListAlternate(fnOnClick, oDiv) {
configureSelectList(oDiv, fnOnClick);
}
The configureSelectList() function
In this function, you can eliminate this line:
if(!fnOnClick) fnOnClick=configureSelectList.clickEvent
That isn't needed any longer. Now, I see something I don't understand:
if (!oDiv) oDiv = configureSelectList.Container;
I didn't see you hook that Container property on in any of the other code. Unless you need this line, you should be able to get rid of it.
The setDiv() function can stay the same.
Not too exciting, but you get the idea - your code really could use some cleanup - are you avoiding the use of a library like jQuery or MochiKit for a good reason? It would make your life a lot easier...
A function's properties are not available as variables in the local scope. You must access them as properties. So, within 'fc' you could access 'myvar' in one of two ways:
// #1
arguments.callee.myvar;
// #2
fc.myvar;
Either's fine...
Try inheritance - by passing your whatever object as an argument, you gain access to whatever variables inside, like:
function Obj (iString) { // Base object
this.string = iString;
}
var myObj = new Obj ("text");
function InheritedObj (objInstance) { // Object with Obj vars
this.subObj = objInstance;
}
var myInheritedObj = new InheritedObj (myObj);
var myVar = myInheritedObj.subObj.string;
document.write (myVar);
subObj will take the form of myObj, so you can access the variables inside.
Maybe you are looking for Partial Function Application, or possibly currying?
Here is a quote from a blog post on the difference:
Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.
If possible, it would help us help you if you could simplify your example and/or provide actual JS code instead of pseudocode.