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

モデル:いいえ値はgetResponse()から返されません

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

。値が返されると、値は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) 
    }) 
} 
関連する問題