官术网_书友最值得收藏!

Classical change detection

Let's take a look at a simple example, which doesn't use any framework. Suppose, we have a model called User, which has a property called name:

class User extends EventEmitter { 
  private name: string;
 
  setName(name: string) { 
    this.name = name; 
    this.emit('change');
  }
 
  getName(): string { 
    return this.name;
  } 
} 

The preceding snippet again uses TypeScript. Do not worry if the syntax does not look familiar to you, we will make an introduction to the language in the next chapter.

The user class extends the EventEmitter class. This provides primitives for emitting and subscribing to events.

Now, let's define a view, which displays name of an instance of the User class, passed as an argument to its constructor:

class View { 
  constructor(user: User, el: Element /* a DOM element */) { 
    el.innerHTML = user.getName();
  } 
} 

We can initialize the view element as shown here:

let user = new User(); 
user.setName('foo'); 
let view = new View(user, document.getElementById('label')); 

As the end result, the user will see a label with the content foo. However, changes in user will not be reflected by the view. In order to update the view when the name of the user changes, we need to subscribe to the change event and then update the content of the DOM element. We need to update the View definition in the following way:

class View { 
  constructor(user:User, el:any /* a DOM element */) { 
    el.innerHTML = user.getName(); 
    user.on('change', () => { 
      el.innerHTML = user.getName();
    }); 
  } 
} 

This is how most frameworks used to implement their change detection before the era of AngularJS.

主站蜘蛛池模板: 大竹县| 香河县| 濮阳县| 临汾市| 高雄县| 洪洞县| 曲水县| 商洛市| 海丰县| 扶沟县| 永春县| 宁城县| 那曲县| 桦川县| 正宁县| 连州市| 三河市| 雅江县| 阿鲁科尔沁旗| 开平市| 绍兴市| 关岭| 余干县| 徐汇区| 益阳市| 陇西县| 万全县| 永善县| 黄骅市| 象山县| 恩施市| 乐山市| 乐亭县| 二连浩特市| 涞源县| 正镶白旗| 宁安市| 孟津县| 衡阳县| 新龙县| 阳西县|