Check out a free preview of the full Vue 2 Internal Features from the Ground Up course
The "Challenge 3: Mini Observer" Lesson is part of the full, Vue 2 Internal Features from the Ground Up course featured in this preview video. Here's what you'd learn in this lesson:
In this challenge, students combine the previous two solutions to create a mini observer.
Transcript from the "Challenge 3: Mini Observer" Lesson
[00:00:00]
>> Evan You: So let's go into exercise 3, now is the time to put the previous two exercises together, okay? And it's actually going to be simpler than you think. So let's combine the previous two functions. So currently we have convert function from exercise 1, we have the autorun function from exercise 2.
[00:00:20]
So lets rename convert into observe, all right? So what observe does it just take any object, observe it, converting them into getters and setters. And inside getters and setters we can do something with dependencies, all right? And then autorun just remains the same from the previous exercise. So where we're using the Dep class and autorun function from exercise two and then what we need to do is copy the over convert from exercise one and modify it so that we hook up the Dep.depend and Dep.notify calls into the getters and setters.
[00:01:01]
Then when these connect, we essentially have created an object when we access a property it collects dependency but call dep.depend. And when we mutate a property by assigning to be it cause dep.notify to trigger changes. Are the dots connecting now? So this is actually how the view update system works, okay?
[00:01:24]
So this is what we want. Let's say we just have a state object with count zero. The finished implementation should observe the state, this will walk through the properties, convert them into getters and setters, and the autorun, inside all autorun, we're still doing just a console log. But notice here, we're accessing state.count.
[00:01:48]
This is just a normal access. But if we have converted the object into getters and setters, this will be invoking the getter here, right? And this is the opportunity where we should call dep.depend. And later on when you mutate this state.count we are invoking the setter, and this is where we should call dep.notify.
[00:02:10]
So exercise 3 is just to fill in the blanks. So notice you can reuse most of the code from exercise 1 and 2. And it should be pretty straightforward up to this point.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops