Asynchronous javascript calls that populate some property

I have a javascript object that includes some lines of images as their property. After an instance of this object, an AJAX call is immediately made to populate this property.

My view, at the same time, is trying to read newly created instances and trying to display this object. As expected, the AJAX call may not have been completed by then, so it will not be able to read the correct image URL.

One solution to this problem is to pass some callback function with an AJAX call that changes the image source code upon completion, but it introduces a lot of model and presentation dependency, and I'm trying to keep my MVC as separate as possible, so my view function right now takes this object as a parameter, reads all properties and shows it.

Creating synchronous AJAX is not an option, because I have quite a few of these objects initialized, and only one will be displayed at a time, so all synchronous AJAX calls will be too expensive due to a compromise.

What is a good way to solve this problem? The view function is something like:

function displayObj(object) {
    var prop1 = object.getProp1();
    // this could be the image file that depends on AJAX result
    var prop2 = object.getProp2(); 
}

, . , , , , , , . , AJAX, , getter, view .

, . !

+5
2

MVC, DOM <img>.

// model object starts loading upon instantiation
var loader = new Loader();

// however the img tag is available immediately.
// the loader will update the src when ajax
// calls complete.
document.body.appendChild(loader.getImg());
0

jQuery, done() , ajax(). ,

var request = $.ajax("example.php");
request.done(notifyWhenSuccess);
request.fail(notifyWhenFailed);

, jQuery, Promise CommonJS. , , jQuery, ajax, . done() , , .

0

All Articles