Monday 10 April 2017

Implementation of monitoring of computed properties in VueJS

In VueJS documentation, the following behavior is mentioned.

Here we have declared a computed property reversedMessage. The function we provided will be used as the getter function for the property

<div id="example">
  <p>Original message: ""</p>
  <p>Computed reversed message: ""</p>
</div>

var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    // a computed getter
    reversedMessage: function () {
      // `this` points to the vm instance
      return this.message.split('').reverse().join('')
    }
  }
})

vm.reversedMessage:

console.log(vm.reversedMessage) // -> 'olleH'
vm.message = 'Goodbye'
console.log(vm.reversedMessage) // -> 'eybdooG'

You can open the console and play with the example vm yourself. The value of vm.reversedMessage is always dependent on the value of vm.message.

You can data-bind to computed properties in templates just like a normal property. Vue is aware that vm.reversedMessage depends on vm.message, so it will update any bindings that depend on vm.reversedMessage when vm.message changes. And the best part is that we’ve created this dependency relationship declaratively: the computed getter function has no side effects, which makes it easy to test and reason about.

From the last para, 2nd sentence, I understand that the VueJS library will monitor the value of the "message" variable and then recomputes "reversedMessage" whenever 'message' changes.

Can anyone explain me, conceptually, how this can be achieved in JS? Is there any specific software design pattern that is being followed? I am curious to know how the JS run-time is made to understand the variables a function depends on. What if my computed property uses multiple variables?

Any examples of such behavior programmed into other systems/libraries/frameworks ??



via Raghavendra Kumar

No comments:

Post a Comment