Tuesday, October 9, 2012

jquery data

Like I've written about previously, Javascript scoping can be tough to wrap your head around, and in general I try to avoid situations where I have to use CreateDelegate in order to have the context I'd "expect", especially during a click or similar event.

Yesterday I realized I had been forgetting about a very powerful tool in the anti-CreateDelegate, let-DOM-objects-carry-the-context-they-need front: jQuery's ".data()"  function. This little beauty lets a developer put key/value pairs "into" the DOM object for easy retrieval later.

Here's a version of some broken code I made yesterday:

for(var i = 0; i < data.length;i++){
    var jqo = $(".templateWrapper .modelTile").clone(true);
    var foo = data[i].value;
    jqo.click(function(){
        alert.text(foo);

    });
    $("#container").append(jqo);
}

The problem was because of the scoping, the text being alert()d was whatever the last value of foo had been, for all the tile objects.

I knew I could make use CreateDelegate object to carry the context, but that seems slightly less robust. Instead, I went back to use the .data() function:

for(var i = 0; i < data.length;i++){
    var jqo = $(".templateWrapper .modelTile").clone(true);
    jqo.data("val", data[i].value);
    jqo.click(function(){
        alert.text(
$(this).data("val"););
    });
    $("#container").append(jqo);
}

That worked and felt great! I'm not sure why I've been shy about using the .data() function; it's easier than CreateDelegate and less hacky than hidden form elements or rereading the content of visible DOM objects.

No comments:

Post a Comment