In the name of unobtrusive scripting, I like to store different key/ 
value things in my class attributes, like

<input type="checkbox" class="checkBlur target-input1-input2-input3">

in this case, the checkbox would blur elements with ids of input1,  
input2 and input3. So I use a dash-separated list to build an array  
of values, with the first value being the key. Now, you may criticize  
this behaviour if you like (and really, I'd welcome it) but my main  
thing here is to ask about a little plugin i wrote after just going  
over to jquery for handling this.
I wanted to be able to get the value of such a classValue, change it,  
and clear it.
First I thought of having three different functions, getClassValue,  
changeClassValue and clearClassValue
but for some reason I didn't really want to clutter the namespace  
with three different functions, I wanted something quite slick, and  
since I almost exclusively use this functionality to just get an  
array with the values, I thought I could have just classValue, that  
always returns the values (of the first object found) and then pass  
in options for changing and clearing if desired. Like this

$(element).classValue('key')  to get values
$(element).classValue('key', {newValue: [array])  to change values
$(element).classValue('key', {clear: true})  to clear values

What do you think? Is it bad to include this extra functionality as  
options?

Andreas


The code (if you find it useful, please do mention any errors)


jQuery.fn.classValue = function(key, settings) {
     settings = jQuery.extend({
         delimiter: '-',
         clear: false,
         newValue: false
     }, settings);
     if (settings.newValue) {
         settings.clear = false;
         if (typeof(settings.newValue) == 'string') {
             settings.newValue = [settings.newValue];
         }
     }

     for (var i = 0; i < this.length; i++) {
         var classAttributes = this[i].className.split(' ');
         for (var j = 0; j < classAttributes.length; j++) {
             var values = classAttributes[j].split(settings.delimiter);
             if (values[0] == key) {
                 var ret = values.splice(1, values.length);
                 if (settings.newValue) {
                     $(this).removeClass(classAttributes[j]).addClass 
(key + settings.delimiter + settings.newValue.join(settings.delimiter));
                 }
                 if (settings.clear) {
                     $(this).removeClass(classAttributes[j]);
                 }
                 return (ret);
             }
         }
     }
     return (false);
};

_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/

Reply via email to