Francois
Francois

Reputation: 93

Jquery plugin and $.ajax

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.

Upvotes: 2

Views: 1132

Answers (2)

red-X
red-X

Reputation: 5128

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

Upvotes: 1

Daniel Mendel
Daniel Mendel

Reputation: 10003

Try storing this in a variable:

        init: function() {
            var that = this;          
            $.ajax({
                type: "GET",
                url: "param.xml",
                dataType: "xml",
                success: that.initOptions
            });                             
            return that;
        },          

Upvotes: 3

Related Questions