JavaScript OOP with jQuery

I have object myObject, inside I have function execute(), inside I have $.ajax({ which have complete: function(xmlHttp){. Inside that function I want to call setResult which is defined in the myObject. How to do that?

function myObject() {
    this.setResult = setResult;
    function setResult(result) {
        this.result = result;   
    }

    function execute() {
         $.ajax({
            complete: function(xmlHttp){
                (?) setResult(jQuery.parseJSON(xmlHttp.responseText));
            }
        });
    }

Answers:

Answer

The standard way to do OOP is to use myObject as a constructor, and extend its prototype object with whatever needs to be inherited.

function myObject() {
    // constructor function
}

myObject.prototype.setResult = function (result) {
    this.result = result;   
}

myObject.prototype.execute = function() {
     $.ajax({
        context: this, // bind the calling context of the callback to "this"
        complete: function(xmlHttp){
            this.setResult(jQuery.parseJSON(xmlHttp.responseText));
        }
    });
}

var obj = new myObject();
obj.execute();

There's no requirement that it be done this way, but it's very common.

You need to keep in mind that the calling context of a function varies based on how that function is called. With respect to the complete: callback, jQuery sets the context, so it won't be your object unless you tell jQuery to make it that object or use some other way to bind the context.

jQuery's $.ajax method gives you a context: property that lets you set the calling context of the callbacks, as I've shown above.

Answer
function myObject() {
    var that = this; // Reference to this stored in "that"
    this.setResult = setResult;

    function setResult(result) {
        this.result = result;   
    };

    function execute() {
         $.ajax({
            complete: function(xmlHttp){
                that.setResult(jQuery.parseJSON(xmlHttp.responseText));
        }
    });
}

Also you can check out jquery proxy and/or bind

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.