2017-10-14 59 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) 
    }) 
}