1

The idea is that I want to loop through these objects and build an HTML structure which will be added to the page. I thought it would be cleaner to do it all in the chain, but apparently I'm not understanding something about the context of this as it evolves through inner loops. I've looked a bit at jQuery.proxy() a bit, but I'm not sure I understand how to apply it here. Maybe there is another way altogether of doing what I'm trying to do here...

var obj = [
    {"id":1213854620001,"name":"item 1","URL":"1213897576001.jpg"},
    {"id":1213854619001,"name":"item 2","URL":"1213890384001.jpg"},
    {"id":1213854618001,"name":"item 3","URL":"1213890378001.jpg"},
    {"id":1213854616001,"name":"item 4","URL":"1213897663001.jpg"},
    {"id":1213854615001,"name":"item 5","URL":"1213897554001.jpg"}
];
$(function() {
    if(obj.length) {
        $("<ul/>",{id:"myID"}).append(function(){
            var that = document.createDocumentFragment();
            $.each(obj,function(index,dataObj){
                $("<li/>",{data:{dataID:dataObj.id},text:dataObj.name}) // this === obj[index] === dataObj, shouldn't it be the [object HTMLLIElement]
                    .live("click",function(event) {
                        openVideo($(event.target).data(dataID));
                    })
                    .append(function() {
                        return $("<img/>",{src:dataObj.thumbnailURL})[0];
                    })
                    .appendTo(that);
            });
            return that;
        }).appendTo("body");
    }
});

function openVideo(str) {
    //console.log(str);
}

The implicit question becomes, why is that empty after my loop? and how can I build this HTML structure with nested loops?

Using the suggestions from the comments, and answers, I built this, which seems to work exactly as it should, reads a little cleaner, and lets jQuery do all the javascript (e.g. documentFragment creation, and manipulation, etc):

$(function() {
    if(obj.length) {
        $("<ul/>",{id:"myID"})
        .delegate("li","click",function(){openVideo($(this).data("dataID"));})
        .append(function() {
            var that = $(this);
            $.each(obj,function(index,dataObj) {
                $("<li/>",{data:{dataID:dataObj.id},text:dataObj.name}).each(function() {                   
                    $("<img/>",{src:dataObj.URL}).appendTo(this);
                    that.append(this);
                })
            });
        }).appendTo("body");
    }
});
12
  • Your use of .live() is incorrect. You really shouldn't be using .live() in the first place. Dec 14, 2011 at 18:08
  • why is .live() incorrect here, the structure isn't in the DOM yet, I'm binding for the future?
    – bodine
    Dec 14, 2011 at 18:13
  • that is referencing a documentFragment. jQuery doesn't like those so much. Dec 14, 2011 at 18:13
  • .live() uses event delegation. You need to provide it a selector and bind to an ancestor, and you only do it once instead of in a loop. It doesn't bind in the future. Dec 14, 2011 at 18:14
  • 1
    ...generally speaking, document wide event delegation isn't the best solution. That's what .live() is. Dec 14, 2011 at 18:20

3 Answers 3

4

this changes meaning as you step into new nested functions. It does not change meaning when you call $() to create a new element.

So immediately inside of

$.each(obj, function(index, dataObj) {

this is the current object over which your looping. Once you get here:

.live("click",function(event) {  // <------  inside of nested function 
    openVideo($(event.target).data(dataID));
})

this is the element on which you clicked.

But calling

    $("<li/>",{data:{dataID:dataObj.id},text:dataObj.name}) 

to create a new li element does not set this to the newly created element.


Also, if you want to save the meaning of this even inside of nested functions, the standard way is to save it to a new variable.

$.each(obj, function() {
    var self = this;

Now self can be used instead of this as the item you're currently "on" anywhere in your loop, even in nested function handlers. Or you can pass index and dataObjects to the each function - same effect.

EDIT

As a comment pointed out, you're using live incorrectly. If you're using jQuery 1.7, you'll want:

$(document).on("click", "li", function(event) {
      openVideo($(this).data(dataID));
});

in your document.ready handler. If all li's that will be clicked will be in a certain div, than select on that div instead of document. If you don't want this click handler to apply to all li's, but only some, then decorate all the li's you want this click handler to apply to with a css class, then instead of passing the filter "li" to on, you'd pass li.yourClass

4
  • problem is it isn't changing to the freshly created LI element, which I'm chaining the subsequent methods to...
    – bodine
    Dec 14, 2011 at 17:53
  • So, I'm still unclear as to why my chained methods are using dataObj instead of the jQuery object created (and returned by) $("<li/>",{data:{dataID:dataObj.id},text:dataObj.name}). Inside a jQuery method chain isn't this supposed to be the selector object at the beginning of the chain?
    – bodine
    Dec 14, 2011 at 18:06
  • @bodine - $("<li/>",{data:{dataID:dataObj.id},text:dataObj.name}) does not set this to the dom element you just created. It's not supposed to. I think you might be mixing up some things. Dec 14, 2011 at 18:11
  • @AdamRackis thank you for steering me in the right direction here. I'm still not quite sure I understand why my UL wasn't getting built with the old method chain approach. Maybe it was related to the funky .live() attachment... Either way thanks for straightening me out on the misuse of .live()!
    – bodine
    Dec 14, 2011 at 21:03
1

$.each sets this for the inner function to be the element iterated (and yes, this is one of the complicated things in Javascript, but your comment can be explained by just referencing each behaviour).

4
  • $("<li/>",{data:{dataID:dataObj.id},text:dataObj.name}) should reset this for the method chain that follows, but that doesn't seem to be the case. Could you please clarify your answer a bit?
    – bodine
    Dec 14, 2011 at 17:57
  • Well, it depends at which exact point you are dealing with this. The line where your comment is, is in the scope of function(index,dataObj){...}, and there this is set to dataObj, which is exactly how $.each behaves. Or do you have problem with this in different point of your code? Which one? this has strong function scope. It is potentially different for every (inner or not) function, and is not inherited from outer scope, ever.
    – user1046334
    Dec 14, 2011 at 18:02
  • I guess my confusion is with the fact that even though there is a comment here (which is effectively a breakpoint in my debugger), I'm still in the method chain, right? So inside those chained methods this should not be dataObj, right?
    – bodine
    Dec 14, 2011 at 18:10
  • Inside those chained methods it is your jquery set containing the <li> element, but is complicated even more, because function(event) { openVideo($(event.target).data(dataID)); } and function() { return $("<img/>", {src:dataObj.thumbnailURL})[0]; } are not chained, they are just some callbacks created on the spot and when they are called (later, maybe never), whoever calls them rules about what will this be (same as $.each ruled about this for function(index,dataObj){ ... }). So read the API documentation to see what this will be for those inner functions, when they are called.
    – user1046334
    Dec 14, 2011 at 18:17
0

The thing is, in prototype based languages, which javascript is one, functions are objects, and objects have properties. So when you use the 'this' keyword, it reverts to the scope of the current prototype. Inside of an 'inline function' (which is actually not a concept in javascript since functions are just objects), this refers to the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.