Question

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.

Was it helpful?

Solution

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());
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top