jQuery has the very cool feature/method ".data", i wonder if there is a way to have the data in the code so that jQuery can use it when the rendering of html is done. Suppose i have a repeater and looping out children, and i want to add some data to those children without using classes etc. Will i have to add javascript to that repeater just to add stuff to the "data of jquery" or is there some better way?
There is the metadata plugin which might do what you are talking about
For example, you can do: (You can pick from different format by setting an option)
<li class="someclass {some: 'data'} anotherclass">...</li>
OR
<li data="{some:'random', json: 'data'}">...</li>
OR
<li><script type="data">{some:"json",data:true}</script> ...</li>
OR
<li data-some="'random'" data-json="'data'">...</li>
After that you can simply do:
var data = $('li.someclass').metadata();
if ( data.some && data.some == 'data' )
alert('It Worked!');
HTML 5 has a new standard for attributes starting with "data-". See here link text.
You could use this to store data and use a selector to parse out the data.
Are you thinking "what better place to store an object's data than on the element itself"?
For example you have a bowl of fruit?
function Fruit(name, color){
this.name = name
this.color = color
}
var apple = new Fruit("apple", "red")
var orange = new Fruit("orange","orange")
var bowl = [apple, orange]
Now you render the fruit bowl on the page?
Fruit.prototype.render = function(){
return createElement('li').html(this.name)
}
$.each(bowl, function(i, fruit){
$('#fruitbowl').append(fruit.render())
}
Ok. Now you can add the object to the element trivially by changing that last line and attaching the actual fruit object to their element renderings thus:
$('#fruitbowl').data('obj', fruit).append(fruit.render())
Which makes it pretty darn easy to access the data when an event occurs. For example change the rendering routine to include a click event:
Fruit.prototype.render = function(){
var el = createElement('li').html(this.name)
el.click(function(){
alert('You clicked on an ' + $(this).data('obj').name)
}
}
Now one can easily argue that it is silly to duplicate the object by attaching it to the elements in this way, since you already have the object both, in the scope of the script, and if you write it right, inside the closure of the object. And these are probably valid arguments. But this, I agree, is pretty cool :-)