MVC:鉴于模型的属性是异步获取的,如何在控制器的构造函数中记录模型的属性值?

时间:2019-11-08 16:37:02

标签: javascript model-view-controller

我正在尝试在我的应用中应用MVC设计模式。

但是,我不确定this.logActivites()的构造函数中Controller的输出为什么是undefined。不过,加载页面后,我可以从控制台轻松完成app.logActivities()

是因为(由于某种原因)尚未提取数据?我该如何解决?

class Model {
         constructor() {
             this.getActivities()
                 .then(json => 
                     this.activities = json.activities
                 )
         }

         async getActivities() {
             const url = 'https://jsonplaceholder.typicode.com/todos/1'
             const response = await fetch(url)
             const json = await response.json()
             return json
         }    
     }

     class View {
         constructor() {}
     }

     class Controller {
         constructor(model, view) {
             this.model = model
             this.view = view

             this.logActivities()
         }

         logActivities() {
             console.log(this.model.activities)
         }              

     }

     app = new Controller(new Model(), new View())

1 个答案:

答案 0 :(得分:1)

它记录未定义,因为在那个时刻它是。 在这里,我展示了一个记录{}的示例,因此您可以看到它是正确的。

例如,如果您的fetch再也没有像fetch("HTTPS://Iambadforever.gone/I/do/not/exist")这样回来了,该怎么办

我做了一个可能的改变

/*jshint esversion: 8 */
class Model {
  constructor() {
    this.getActivities()
      .then(json =>
        this.activities = json.activities
        // possibly this?
        this.logActivities();
      );
  }

  async getActivities() {
    const url = 'https://jsonplaceholder.typicode.com/todos/1';
    const response = await fetch(url);
    const json = await response.json();
    return json;
  }
  
  logActivities() {
    console.log(this.activities);
  }
}

class View {
  constructor() {}
}

class Controller {
  constructor(model, view) {
    this.model = model;
    this.view = view;

    //  this.logActivities();
  }


}
let m = new Model();
console.log(m);
m.activities = {};
let v = new View();
console.log(v);
let app = new Controller(m, v);