简体   繁体   中英

Creating custom JavaScript object from data returned by jQuery AJAX request

I want to create a custom javascript object which contains data returned from a jQuery AJAX request, but I don't know which is the right way to do it. I was thinking maybe one way could be to include the AJAX request inside the constructor function so the object is created like this:

// Constructor function
function CustomObject(dataUrl) {
    var that = this;

    $.ajax(dataUrl, {
        success: function (json) {
            that.data = $.parseJSON(json);
        }
    });
}

// Creating new custom object
var myObject = new CustomObject('http://.....');

Another way may be to use a function which does the AJAX and then returns the new object based on the data from the AJAX response.

function customObject(dataUrl) {
    // Constructor function
    function CustomObject(data) {
        this.data = data;
    }

    $.ajax(dataUrl, {
        success: function (json) {
            var data = $.parseJSON(json);
            return new CustomObject(data);
        }
    });
}

// Creating new custom object
var myObject = customObject('http://.....')

I would like to know what is the best practice when doing something like this, as well as advantages/disadvatages of different methods. Maybe you can point me to some article or example on something similiar to what I am trying to do.

Thanks in advance.

I think this would be a better approach, it makes your CustomObject only knowledgeable about the data it contains. Here you delegate the work of creating objects to a factory, and pass in a callback to get a reference to the created object, since ajax is asynchronous. If you don't mind making it synchronous, then the createCustomObject function can just return the instance, and the callback can be removed.

function CustomObject(data) {
    this.data = data;
}

var factory = (function(){
   function create(dataUrl, objectClass, callback){
       $.ajax({
           url: dataUrl,
           success: function (data) {
              callback(new objectClass(data));
            }
           });
   }
   return{
      createCustomObject: function(dataUrl, callback){
          create(dataUrl, CustomObject, callback);
      }
   };
})();

// Creating new custom object
var myObject = null;
factory.createCustomObject('http://..', function(customObject){
   myObject = customObject;
});

我认为第二种方法更好,因为只有在脚本完全准备好后才创建新的CustomObject (即,它具有AJAX请求中需要的数据),然后您才创建它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM