Then in Vue, the signals are called refs, and you create one with the ref function, and what you get back is an object. The object has a dot value that looks like it's a property, but actually under the hood it's implemented with a getter function and a setter function. So it's, again, two function calls, even though it doesn't look like that in here. You can just do the plus plus, and actually what happens is two function calls. In the template, you don't have to put the value, but that's because Vue parses it and handles it for you.
Then there's also in Svelte, for example, the signal implementation is called runes, but we don't have time to go into that much. Okay. So let's start building something. I'm going to have to go quite fast because the time limit is 20 minutes, so I hope you can follow along and I'll try to explain. So first we will begin by defining the function signal, which acts as the container for the value. We will return an object that has a getter method and a setter method for the value. So in this case, we are going to do it kind of like a little bit of Vue.js way of using the getter and setter methods. But at this point, what we have is not that exciting yet. It's basically like a variable that we can instantiate, and then we can change the value. And if we console.log like this, and if we then execute, yeah, it's not that exciting.
But earlier when I said that the function knows when it's called, it's nothing that exciting, just that we can execute code here. That's basically what I mean. We can execute code here so we can see the get and set methods get called when the value is used inside the function. Now, if you remember back from the slide, there were two points. So the first one was to know when a value changes, sorry, know who uses the value. So to get started with that, here in the getter method, we need to track who uses the value. So for that we will implement a track function, which will take a signal as a parameter. And then we need a place to store somehow the usage. So let's define a usage as we will use a WeakMap for this. And the reason we are using WeakMap is that instead of like a normal just object, we can use the signal object itself as the key. So we can check if there is already something in there. And if not, then we can set it as an empty array. And then going on, we will get, and then we have the array and we will put something in the array. But what should we put there? Okay. Now, the goal here is that we can get rid of the second console log.
Comments