- Switching to Angular(Third Edition)
- Minko Gechev
- 265字
- 2021-07-02 15:23:33
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.
- C#高級編程(第10版) C# 6 & .NET Core 1.0 (.NET開發經典名著)
- jQuery Mobile Web Development Essentials(Third Edition)
- 算法訓練營:入門篇(全彩版)
- Visual Basic程序設計(第3版):學習指導與練習
- 深入淺出Windows API程序設計:編程基礎篇
- Hands-On Enterprise Automation with Python.
- FFmpeg入門詳解:音視頻原理及應用
- Nginx Lua開發實戰
- Internet of Things with ESP8266
- R Data Science Essentials
- Machine Learning for Developers
- Java EE Web應用開發基礎
- 深入實踐DDD:以DSL驅動復雜軟件開發
- 算法秘籍
- Java EE項目應用開發