I’ve been messing around with jQuery plugin code and I’m trying to put all of my common variables into a single object for easy access. I have included a few examples below on how I’ve done this, but I’m wondering how others deal with this problem.
Lets say I have this
var x = function(options){
var defaults = {
ulist : $('ul#list'),
listLen : $('ul#list').children().length
}
$.extend(options, defaults);
// do other stuff
}
What I’m trying to do is use the ulist object in as a base, then find the number of li‘s
I guess I could do this:
var x = function(options){
var defaults = {
ulist : $('ul#list'),
listLen : 0
}
defaults.listLen = defaults.ulist.children().length;
$.extend(options, defaults);
// do other stuff
}
or this:
var x = function(options){
var defaults = {
ulist : $('ul#list')
};
var defaults2 = {
listLen : defaults.ulist.children().length
}
$.extend(defaults, defaults2);
$.extend(options, defaults);
// do other stuff
}
The above code samples are just thrown together, and only meant to get the idea across to you. Anyway, is there a better way to do this?
I would say this version that you posted, but no need to initialize
listLento0.EDIT:
Your second solution would work too, but no need to do two calls to
$.extend(). It can accept more than one object.Your first solution still seems better.
EDIT:
(As pointed to, you can use a function. Although I’d still assign the function outside the initialization of the
defaultsobject, so you can add the function call operator()at the end, and call it like a property.Now you can access
defaults.listLenlike a property and get the result of the function call, sort of like calling.lengthon a jQuery object.