3

I'd like to add a property to the jQuery object and hence attach it to the DOM without polluting the DOM. In casu, the property i'd like to add is called 'hue'. (But let's not think of this property as a color )

Ofcourse, there's the possibility to use jQuery's 'data' function, and this works beautifully. However, it makes my code less readable.

$("#a").data("hue","123");
$("#b").data( $("#a").data("hue")  );

I've also managed to create a getter and setter function, which is already significantly more readable.

$("#a").setHue(123);
$("#b").setHue(  $("#a").getHue()   ); 

Ultimately, what I'd like to achieve is to be able to write my jQuery/javascript code as such:

$("#a").hue(123);
$("#b").hue(  $("#a").hue()   ); 

However, it doesnt work and when evaluating it in firebug, my browser crashes.

Here's the code I've created so far. The getHue() and setHue('123') works, the Hue() doesn't.

//extend the jQuery object with some extra properties for sake of readability
(function($)
{
    $.fn.setHue = function(hue_value)
    {
        this.hue=hue_value;
        return this;
    };

    $.fn.getHue = function()
    {
        return this.hue;
    };

    $.fn.hue = function(hue_value)
    {
        if ( typeof hue_value === 'undefined' ){
            return this.getHue();
        } else {
            this.setHue();
            return this;
        }
    };


})(jQuery);

I've tried researching Googling, reading paper books and and reading the jQuery API on plugin creation. But, these all focus on creating more functional plugins, manipulating DOM elements. It might be that I just haven't google'd on the right keywords.

Ideogram
  • 1,265
  • 12
  • 21
  • din't test your code, but shouldn't you pass the `hue_value` when you call `this.setHue()` in your `$.fn.hue` function? Such that: `this.setHue(hue_value);` – Lorenzo Marcon Feb 07 '14 at 09:20

1 Answers1

1

like this? http://jsbin.com/doxa/1/edit

(function($){

  $.fn.hue = function (value) {
    if(value) {
      return this.each(function() {
        $(this).data('hue', value);
      });
    }
    return this.data('hue');
  };

})(jQuery);

$(function () {
  $('#a').hue('xxx');
  $('#b').text($('#a').hue());
});
s4ty
  • 297
  • 3
  • 7
  • Let's note the differences betweeen your approach (that works) and mine (that didn't work) >> (1) You make use of jQuery's **data** function. Apparently, this is also important for memory-leaks and handling unforeseen situations. >> (2) Your code makes use of jQuery's **each** method for returning (chaining) and setting the propety. Which is a good practice in plugin-writing that I overlooked. – Ideogram Feb 07 '14 at 13:41