2

I'm trying to do write a jQuery plugin based on a prototype pattern.

My problem is when I use the $.ajax function to load an xml file, I loose the this object.

For example this work :

Plugin.prototype = {        
        defaults: {
            message: 'Hello world!'             
        },
        init: function() {              
            this.setStyleAndOptions();
            return this;
        },
        setStyleAndOptions: function() {                
            alert("setStyleAndOptions : ");
        }
}

But that doesn't, I get an error saying "this.setStyleAndOptions is not defined" :

Plugin.prototype = {

        defaults: {
            message: 'Hello world!'
        },
        init: function() {              
            $.ajax({
                type: "GET",
                url: "param.xml",
                dataType: "xml",
                success: this.initOptions
            });                             
            return this;
        },          
        initOptions: function(dataxml) {        
            // Error occured here, I suppose "this" is not the plugin anymore
            this.setStyleAndOptions();
        },
        setStyleAndOptions: function() {                
            alert("setStyleAndOptions");
        }
}

Thanks for your help.

2 Answers 2

3

Try storing this in a variable:

        init: function() {
            var that = this;          
            $.ajax({
                type: "GET",
                url: "param.xml",
                dataType: "xml",
                success: that.initOptions
            });                             
            return that;
        },          
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is that this is the function on the moment of the error. You could try it with the apply or call function:

Plugin.prototype = {

    defaults: {
        message: 'Hello world!'
    },
    init: function() {              
        $.ajax({
            type: "GET",
            url: "param.xml",
            dataType: "xml",
            success: function(){
                this.initOptions.apply(this, arguments);
            }
        });                             
        return this;
    },          
    initOptions: function(dataxml) {
        this.setStyleAndOptions();
    },
    setStyleAndOptions: function() {                
        alert("setStyleAndOptions");
    }
}

1 Comment

Thanks. That was the right direction I just had to declare another variable because in the success function, this is the function. But a mix with the first answer did the trick

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.