jQuery Plugin - Keep options object separate - javascript

I created a jQuery plugin that was working great until I started testing it with more than one object on a page. The problem is that the options object passed to each new plugin object is not always the same one associated with that specific object when I access it from inside a function in the plugin. I have a feeling that I am missing something very simple, so the code might make things more clear.
Method used to create the plugin
$.fn.myPlugin = function(options) {
return this.each(function() {
var opts = $.extend({}, $.myPlugin.defaults, options);
new $.myPlugin($(this), opts);
});
}
Function that accesses the options object
$.myPlugin = function($textbox, options) {
function doSomething($textbox) {
alert(options.someProperty);
}
}
No matter what options.someProperty was when I created the plugin. The call to doSomething inside the plugin will always return the someProperty of the first options object in the first plugin object I created for example:
$textbox.focus(function() { doSomething($textbox); } );
This will always return the same someProperty even if different objects with different options objects are focused.
I hope I have made this clear enough. Let me know if you need anymore details.

You're giving the plugin a reference to the same options object for all of the elements.
Try the following:
return this.each(function() {
new $.myPlugin($(this), $.extend({ }, options));
});
This will copy the members of the options object to a new object each time. If your options object has other objects nested within it, you might need a deep copy, like this: $.extend(true, { }, options)
EDIT: You need to extend the options object inside the each method. Otherwise, you'll still have the same object for all of the elements.

Try changing
function doSomething($textbox) {
to
var doSomething = function($textbox) {
to ensure that you are creating separate doSomething methods that use separate closures. (the first version will create a single function the first time it's called, and reuse that function and its closure)

Related

extending jQuery functionality specifics on variations

I understand I can extend jQuery in two forms:
1)
jQuery.fn.extend({
variation1: function(){
...
}
});
I use this like $(selector).variation1();
2)
and custom function
jQuery.variation2 = {
something: function(){
var execute = function(){
...
}
}
}
I use this like $.variation2.something()
My questions are:
In the first case, I was unable to call functions without a selector; this code caused errors $.variation1(); Is this correct? meaning, is there a way to call these functions without an element selector?
In the second case, how could I initialize variation2 with options? The reason I ask this is because in MooTools, when creating a class, we can initialize the class like:
var jsClass = new Class({
Implements: [Options],
options: {
},
initialize: function(options){
this.setOptions(options);
}
});
we call it, and initialize with custom options like
new jsClass({option1: this, option2: that})
So in the MooTools example the class instance executes options by default. Going back to the question, is there a way to do similar in jQuery?
Thanks in advance
The two variations are distinct as you have noticed. jQuery.fn provides the set of functions that are applied to a jQuery QuerySet object (the result of applying a jQuery selector). jQuery.* could simply be thought of as global static objects, including (sometimes) functions that are accessible to anyone who has access to the jQuery object.
To initialize variation 2, I would do something like:
jQuery.variation2 = (function() {
var a = ...;
var b = ...; // other initialization
return {
something: function() {
...
}, ...
};
})();
You could use closures in similar ways to provide initialized code.

How to make a jQuery plugin function callable for stand-alone use, that does not operate on a collection

I read the jquery documentation of plugin authoring and am familiar with that. However, the examples given always operate on a set of previously matched elements. I want to create a function that can do both:
// example usage of my to-be-created plugin function
// this is the way described in the docs, and I know how to do that
$("a").myFunction ()
// but I also want to be able to call the function without a collection:
$.myFunction ();
If $.myFunction ()is called without a collection to operate on, it would create it's own collection of what elements to match - kind of an initialization process (but not necessarily run only once). Also, $.myFunction ()should maintain chainability.
The pseudocode of what I want to achieve:
// [...]
function myFunction (): {
if (notCalledOnACollection) {
// this should run when called via $.myFunction ()
$elements = $("a.myClass");
}
else {
$elements = $(this);
}
return $elements.each (function () {
// do sth. here
});
}
I would really like to keep all of the functions implementation/functionality within a single function definition, and not have two separately named functions or two equally named functions in two separately places within the jQuery object.
And of course I could add a parameter myFunction (do_init) that indicates what branch of the if statement to execute, but that would clutter my argument list (I want to use that approach for multiple plugins, and there will be argumentes to myFunction () that I just left out here for simplicity).
Any good suggestions?
By simply adding another reference in the plugin definiton, you can easily use the standard plugin code:
(function( $ ) {
$.myPlugin = $.fn.myPlugin = function(myPluginArguments) {
if(this.jquery)
//"this" is a jquery collection, do jquery stuff with it
} else {
//"this" is not a jquery collection
}
};
$.fn.myPlugin.otherFunc = function() {
};
})( jQuery );
The only difference here is the $.myPlugin = part which allows you to directly call your plugin without running jquery's selector function. Should you decide you need other functions or properties, you can create them as properties of your plugin.
Usage:
//using a selector (arguments optional)
$(".someClass").myPlugin();
//using the options variable - or whatever your arguments are
$.myPlugin({id: "someId"});
//accessing your other functions/properties
$.myPlugin.otherFunc();

How to add functions to some jQuery objects, but not others?

Let's say I have a <ul> list:
<ul class="products">
...
</ul>
I want to select it with jQuery, then add some functions to that object. For example, I'd like to add an addProduct(productData) function and a deleteProduct(productId) function. However, I'd like the functions to only be added to the object that's returned by the selector. So for example, something like this:
var productList = $.extend($('ul.products'), {
addProduct: function(productData) {
// add a new li item
},
deleteProduct: function(productId) {
// delete li with id
}
});
How would I do this using jQuery? The key point here is that I only want to add the functions to an instance returned by a jQuery selector. In other words, I don't want to modify jQuery's prototype or create a plugin, since those will make the functions available across everything, whereas I only want to add the functions to one specific instance.
If you only want the addProduct and deleteProduct methods to feature on that single jQuery object, then what you've got will work fine; but you'll have to keep a reference to that jQuery object/ only use it once, to preserve the existance of the addProduct and deleteProduct methods.
However, these addProduct and deleteProduct methods are unique to that particular jQuery object; the methods won't exist on any other jQuery objects you create;
var productList = $.extend($('ul.products'), {
addProduct: function(productData) {
// add a new li item
},
deleteProduct: function(productId) {
// delete li with id
}
});
// Using this particular jQuery object (productList) will work fine.
productList.addProduct();
productList.removeProduct();
// However, addProduct() does not exist on new jQuery objects, even if they use
// the same selector.
$('ul.products').addProduct(); // error; [object Object] has no method 'addProduct'
The best way do to this would be to go-back-to-basics and define separate addProduct and deleteProduct functions, which accept a jQuery object. If you wanted to restrict these functions to they only worked on the ul.products selector, you could do;
function addProduct(obj) {
obj = obj.filter('ul.products');
// do something with `obj` (its a jQuery object)
}
This approach would be recommended as it keeps the jQuery.fn API consistent; otherwise you'd be adding addProduct and removeProduct to some jQuery.fn instances but not others, or making their usage redundant in others. With this approach however addProduct and removeProduct are always there, but don't get in anyones way if they don't want to use them.
Historical Notes
This answer was originally written in November 2011, when jQuery 1.7 was released. Since then the API has changed considerably. The answer above is relevant to the current 2.0.0 version of jQuery.
Prior to 1.9, a little used method called jQuery.sub used to exist, which is related to what you're trying to do (but won't help you unless you change your approach). This creates a new jQuery constructor, so you could do;
var newjQuery = jQuery.sub();
newjQuery.fn.addProduct = function () {
// blah blah
};
newjQuery.fn.deleteProduct = function () {
// blah blah
};
var foo = newjQuery('ul.products');
foo.deleteProduct();
foo.addProduct();
var bar = jQuery('ul.products');
bar.deleteProduct(); // error
bar.addProduct(); // error
Be careful though, the $ method alias would reference the old jQuery object, rather than the newjQuery instance.
jQuery.sub was removed from jQuery in 1.9. It is now available as a plugin.
You can make your own jQuery methods as follows:
$.fn.addProduct = function(){
var myObject = $(this);
// do something
}
// Call it like:
$("ul.products").addProduct();
This is a bit tricky though because you are making methods that are very specific to lists. So, to be sure you should at least add some checking on the object's type and handle the code correctly if the current object is, let's say an input element.
An alternative is to make a normal Javascript method that receives the list as a parameter. That way you can make a more list specific method.
I think you want to add a function to that DOM Object.
$(function(){
// [0] gets the first object in array, which is your selected element, you can also use .get(0) in jQuery
$("#test")[0].addProduct = function(info){
alert("ID: " + this.id + " - Param: " + info);
};
$("#test")[0].addProduct("productid");
});
Above script wil alert "ID: test - Param: productid"
A live example: http://jsfiddle.net/jJ65A/1/
Or normal javascript
$(function(){
document.getElementById("test").addProduct = function(info){
alert(info);
};
});
I think may be just using delegate in jQuery:
$(".parentclass").delegate("childclass","eventname",function(){});

Writing jQuery plugin -- multiple instantiation

I have a question regarding the local variables for my jQuery plugin. I am pretty sure if I declare them outside the main jQuery function register, then every time the plugin is called it will redefine the variables.
Example:
(function($){
jQuery.fn.test = function(options){
if ( options ) {
$.extend( settings, options );
}
this.each(function(i,item){
// do whatever i am going to do
});
};
var settings = {
value1: "hello",
value2: "word"
};
})(jQuery);
Say that $(object).test({value1:'newterm'}); is called multiple times.. Am I correct in thinking that every time that method is called, that it will override the settings with the most recently declared settings?
If i want multiple instances of my plugin, do I need to declare everything within the scope of the main jQuery.fn.test = function(){//here} method?
Yes, that is correct, because $.extend will modify settings which is in the closure scope exposed when the jQuery initialization function sets up .test on the global object jQuery. That closure scope is the same everytime you execute .test; therefore, all objects will retain changes.
It depends on the order you pass objects to $.extend. The first (target) object passed will be modified, in your case the settings object. If you want to keep the defaults:
$.extend(options, settings);
Or to get a brand new object:
var newoptions = $.extend({}, options, settings);

Is it possible to write a second non-static, selecting, priviledged function in a JQuery Plugin?

Almost all of the examples in the jQuery tutorials that I've read, usually use one major public function for their selecting plugin. When I say 'selecting' plugin, I mean one that is not simply a static function extended onto jQuery.
For example:
(function($) {
jQuery.fn.actionList = function(options) {
var opts = $.extend({}, $.fn.actionList.defaults, options);
return this.each(function(){
alert(this);
});
};
$.fn.actionList.defaults = {
listHtml: '<div>Set the list html</div>'
};
})(jQuery);
but not:
jQuery.log = function(message) {
if(window.console) {
console.debug(message);
} else {
alert(message);
}
};
This works fine for most things, but what I would like to do is be able to call a second function on the object returned from the first call.
var actionBox = $('actionBox').actionList(options);
//Many light-cycles later
actionBox.refreshData(data);
or maybe even:
$('actionBox').actionList(options);
// laaateerr
$('actionBox').actionList.refreshData(data);
I'm guessing one or both of these is not possible or, at least not advisable, but I'm only now getting into the deepest aspects of jQuery and javascript.
Could someone explain how to do this, or if it's not possible or advisable, why? and what they would do instead?
Thanks for reading!
I'm not quite sure what you're getting at, but you can call a second function on the object returned from the first function - in fact, it is very much encouraged to return a jQuery object from your plugins, and the reason why you can chain commands in jQuery.
Using your examples
var actionBox = $('actionBox').actionList(options);
//Many light-cycles later
actionBox.refreshData(data);
would work fine, so long as both .actionList() and .refreshData(data) commands both return a jQuery object.
And
$('actionBox').actionList.refreshData(data);
would need to be
$('actionBox').actionList().refreshData(data);
EDIT:
Looking at the jQuery source code,
jQuery.fn = jQuery.prototype = {
/*
Load of 'property' functions of jQuery object...
*/
}
so, adding properties (a.k.a plugins) to jQuery.fn extends the prototype of the jQuery object. When you call
$(selector, context);
a new jQuery object is returned, using the init property function of the jQuery object
jQuery = window.jQuery = window.$ = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
I think I've got a plugin that might be very useful for you. It allows you to apply any constructor/object to jQuery as it's own namespace AND you can use 'this' as you would normally with jQuery to refer to the object set. Using this[methodName] will call a method on your object, etc.
http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js
Some code samples are here:
http://groups.google.com/group/jquery-dev/browse_thread/thread/664cb89b43ccb92c/34f74665423f73c9?lnk=gst&q=structure+plugin+authoring#34f74665423f73c9
It's about halfway down the page.
I hope you find it useful!

Categories