开发者

jQuery extension (scope?) question

开发者 https://www.devze.com 2022-12-12 16:43 出处:网络
I have some confusion over a jQuery extension not working as I\'d expect. I have the following function defin开发者_运维技巧ed:

I have some confusion over a jQuery extension not working as I'd expect. I have the following function defin开发者_运维技巧ed:

$.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?


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");
        });
    });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消