views:

46

answers:

1

I have some confusion over a jQuery extension not working as I'd expect. I have the following function defined:

$.fn.poster = function() {
    this.each(function() {
        self = $(this);
        self.click(function() {
            /* does stuff */
            $.post(url, data, function(d, t) { handle_storage(d, t, self); }, "json");
        });
    });
}

handle_storage = function(storages, status, caller) {
    container = $("<div>");
    $("<span>").poster().html(storage.name).appendTo($("<li>").addClass("folder").appendTo(container));
}

$(function() {
    $("li.storage span").poster();
});

The initial call to poster() in the ready function works, but inside the handle_storage() callback, I get a "poster() is undefined" error. What gives?

+3  A: 

I'm not really sure how you mean, but you probably just need to return this to continue the chaining:

$.fn.poster = function() {
    return this.each(function() {
        self = $(this);
        self.click(function() {
            /* does stuff */
            $.post(url, data, function(d, t) { handle_storage(d, t, self); }, "json");
        });
    });
}
David
doh. Yeah. I just put "return this;" at the end of the $.fn.poster() definition and all is well. Thank you.
Wells
yes, or do as I wrote, put return before this.each.. either way will work.
David
Great answer. His function was returning `undefined`. I would also add `var` so it reads `var self = $(this);` scoping it to that function. Right now it is global.
Doug Neiner