美文网首页
Reactivity in the Wild

Reactivity in the Wild

作者: 7dbe8fdb929f | 来源:发表于2020-09-03 11:34 被阅读0次

If you begin to understand what you are without trying to change it, then what you are undergoes a transformation.
-- Jiddu Krishnamurti

In this article, we want to achieve something like Vue, to perform dependency-tracking and change-notification when properties are accessed or modified, by adding getter/setters which are invisible to the user.

<template>
  <div>Clicked {{count}} times!</div>
  <button type="button" id="counter-button">Click me!</button>
</template>
<div id="app"></div>
const data = {
  message: "a",
  count: 0,
}
function render() {
  const template = document.querySelector("template")
  let content = template.innerHTML
  content = content.replace(/{{(\w+)}}/g, (all, key) => {
    return data[key]
  })
  document.getElementById("app").innerHTML = content
  document.getElementById("counter-button").addEventListener("click", () => {
    data.count++
  })
}

We will walk through all of properties and convert them to getter/setters using Object.defineProperty, this is an ES5-only and un-shimmable feature.

function defineReactive(obj, key, val) {
  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return
  }

  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set

  Object.defineProperty(obj, key, {
    get: function reactiveGetter () {
      const value = getter ? getter.call(obj) : val
      return value
    },
    set: function reactiveSetter (newVal) {
      const value = getter ? getter.call(obj) : val
      if (newVal === value) {
        return
      }
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      // update dom
      render()
    },
  })
}
Object.keys(data).forEach(key => {
  defineReactive(data, key, data[key])
})
render()

相关文章

  • Reactivity in the Wild

    If you begin to understand what you are without trying to...

  • Wild nights-wild Nightsby Emi

    Wild nights-wild Nights Were I with thee Wild Nights shou...

  • 野性的呼唤~15

    3 The wild animal 3 野性 The wild animal was strong in Buck...

  • Vue3响应式 API:进阶(学习笔记)

    shallowRef() ref()[https://cn.vuejs.org/api/reactivity-co...

  • {英语}野猪和狐狸

    THE WILD BOAR AND THE FOX 野猪与狐狸 A Wild Boar was engaged i...

  • 【伊索寓言故事】野猪和狐狸

    THE WILD BOAR AND THE FOX 野猪与狐狸 A Wild Boar was engaged i...

  • WILD

    忽然的失重感让她猛的睁开双眼,看一眼天色,还是凌晨吧,她无声息的再次闭上眼睛。继而沉沉入睡。 手机嗡嗡作响,单调反...

  • Into the wild

    最近黑狗常常来陪伴 所以疯狂的找寻精神食粮 囫囵吞枣导致只是饥饿后的更加饥饿空虚过后的无尽空虚 于是不再理会那些心...

  • In The Wild

    If you want something in life, reach out and grab it.

  • Into the wild

    所以当他背着巨大的行囊,风尘仆仆的一路无所畏惧,天际线只有他一个人的身影,我才忽然明白,原来生活有很多很多种活法,...

网友评论

      本文标题:Reactivity in the Wild

      本文链接:https://www.haomeiwen.com/subject/xnynsktx.html