2017-10-14 60 views
0

我很苦恼我的第一个香草JS MVC应用程序。我的模型向服务器发出一个AJAX请求,然后控制器更新视图,但不等待AJAX​​承诺解决,因此它只是更新视图而没有任何内容。我怎样才能通知控制器的异步解决?Vanilla JS MVC - AJAX成功时从模型中通知控制器

控制器:

function DeadController() { 
     this.model = new DeadModel(); 
     this.view = new DeadView(); 
     this.updateView(); 
    } 
    DeadController.prototype.updateView = function() { 
     this.view.render(this.model.data); 
    } 

型号:

function DeadModel() { 
    this.uri = 'api' + window.location.pathname; 
    this.data = this.getResponse(this.uri); 
} 
DeadModel.prototype.getResponse = function(uri) { 
    $.get(uri, (response) => { 
     return response; 
    }); 
} 

回答

2

没有值从getResponse()返回。当返回值时,该值应该是一个jQuery承诺对象返回$.get()

DeadModel.prototype.getResponse = function(uri) { 
    return $.get(uri); // `return` the jQuery promise object 
} 

DeadController.prototype.updateView = function() { 
    this.model.data // jQuery promise object returned from `$.get()` 
    .then(this.view.render) // pass response data to `this.view.render` 
    .fail(function(err) { // handle error 
     console.error(err) 
    }) 
}