2

I am trying to write a plugin in jQuery, but I am getting "undefined is not a function" in this part:

(function($) {
    $.fn.build = function(options){
        var settings = $.extend({
            x: 0,
            y: 0,
            type: 0
        }, options);

        $.post("/build", { x: settings.x, y: settings.y, type: settings.type}, function(data) {
            // Return JSON array
            if(data['doBuild'] == 'true') {
                this.append("<div class='item' style='left:"+settings.x+"px; top:"+settings.y+"px;'></div>"); // ERROR ON THIS LINE
            }
        },'json');  

        return this;
    };
}(jQuery));

I think that it has to do with the 'this' statement, but I don't understand the error. Why doesn't it work?

0

1 Answer 1

4

this references the jqXHR object within $.post's callback. It looks like you just need to save a reference to your outer this:

    var that = this;
    $.post("/build", { x: settings.x, y: settings.y, type: settings.type}, function(data) {
        // Return JSON array
        if(data['doBuild'] == 'true') {
            that.append("<div class='item' style='left:"+settings.x+"px; top:"+settings.y+"px;'></div>");
        }
    },'json'); 

or you can use $.proxy:

    $.post("/build", { x: settings.x, y: settings.y, type: settings.type}, $.proxy(function(data) {
        // Return JSON array
        if(data['doBuild'] == 'true') {
            this.append("<div class='item' style='left:"+settings.x+"px; top:"+settings.y+"px;'></div>");
        }
    }, this),'json'); 
Sign up to request clarification or add additional context in comments.

1 Comment

I suspected that! I just didn't know how to reference the outer 'this'... I should have taught about saving it to a variable. Thanks, I will try it now!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.