<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title>Remywwo</title>
        <link>https://remywwo.github.io/</link>
        <description>Remywwo' Blog</description>
        <lastBuildDate>Sun, 12 Apr 2026 10:23:50 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <copyright>CC BY-NC-SA 4.0 2021 © Remywwo</copyright>
        <item>
            <title><![CDATA[简易响应式数据实现]]></title>
            <link>https://remywwo.github.io/posts/simple-reactive</link>
            <guid>https://remywwo.github.io/posts/simple-reactive</guid>
            <pubDate>Mon, 27 Mar 2023 16:00:00 GMT</pubDate>
            <description><![CDATA[通过 Dep 类和 Object.defineProperty 实现一个简易的响应式数据系统，理解 Vue 等框架中数据响应式的核心原理]]></description>
            <content:encoded><![CDATA[<p>[[toc]]</p>
<pre><code class="language-js">let data = { price: 5, quanitity: 2 }
let target, total, salePrice

class Dep {
  constructor() {
    this.subscribers = []
  }

  depend() {
    if (target &amp;&amp; !this.subscribers.includes(target)) {
      console.log('target ', target)
      this.subscribers.push(target)
    }
  }

  notify() {
    this.subscribers.forEach(sub =&gt; sub())
  }
}

const deps = new Map()

Object.keys(data).forEach((key) =&gt; {
  // let internalValue = data[key]
  // const dep = new Dep()
  // Object.defineProperty(data, key, {
  //   get() {
  //     dep.depend()
  //     return internalValue
  //   },
  //   set (newVal) {
  //     internalValue = newVal
  //     dep.notify()
  //   }
  // })
  deps.set(key, new Dep())
})

const data_without_proxy = data

data = new Proxy(data_without_proxy, {
  get(obj, key) {
    console.log('proxy get...')
    deps.get(key).depend()
    return obj[key]
  },
  set(obj, key, newVal) {
    console.log('proxy set...')
    obj[key] = newVal
    deps.get(key).notify()
    return true
  }
})

function watcher(myFunc) {
  console.log('run watcher...')
  target = myFunc
  target()
  target = null
}

watcher(() =&gt; {
  console.log('total watcher...')
  total = data.price * data.quanitity
})

watcher(() =&gt; {
  console.log('salePrice watcher...')
  salePrice = data.price * 0.9
})

deps.set('discount', new Dep())
data.discount = 5

watcher(() =&gt; {
  console.log('salePrice watcher2...')
  salePrice = data.price - data.discount
})
</code></pre>
]]></content:encoded>
            <author>onlyprobie@gmail.com (Remywwo)</author>
        </item>
    </channel>
</rss>