{"action":"created","issue":{"url":"https://api.github.com/repos/youngwind/blog/issues/84","repository_url":"https://api.github.com/repos/youngwind/blog","labels_url":"https://api.github.com/repos/youngwind/blog/issues/84/labels{/name}","comments_url":"https://api.github.com/repos/youngwind/blog/issues/84/comments","events_url":"https://api.github.com/repos/youngwind/blog/issues/84/events","html_url":"https://github.com/youngwind/blog/issues/84","id":172268810,"number":84,"title":"vue早期源码学习系列之一：如何监听一个对象的变化","user":{"login":"youngwind","id":8401872,"avatar_url":"https://avatars.githubusercontent.com/u/8401872?v=3","gravatar_id":"","url":"https://api.github.com/users/youngwind","html_url":"https://github.com/youngwind","followers_url":"https://api.github.com/users/youngwind/followers","following_url":"https://api.github.com/users/youngwind/following{/other_user}","gists_url":"https://api.github.com/users/youngwind/gists{/gist_id}","starred_url":"https://api.github.com/users/youngwind/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/youngwind/subscriptions","organizations_url":"https://api.github.com/users/youngwind/orgs","repos_url":"https://api.github.com/users/youngwind/repos","events_url":"https://api.github.com/users/youngwind/events{/privacy}","received_events_url":"https://api.github.com/users/youngwind/received_events","type":"User","site_admin":false},"labels":[{"id":451914258,"url":"https://api.github.com/repos/youngwind/blog/labels/Vue","name":"Vue","color":"4fc08d","default":false}],"state":"open","locked":false,"assignee":null,"assignees":[],"milestone":null,"comments":5,"created_at":"2016-08-20T12:26:50Z","updated_at":"2016-10-28T02:54:06Z","closed_at":null,"body":"# 前言\r\n我们都知道，要想精通前端领域，研究分析成熟的框架是必不可少的一步。很多人可能都有这样的体会：“很努力地去阅读一些热门框架的源码，但是发现难度太高，花了很多时间却得不到什么，最终不得不放弃。”\r\n我也一直被这个问题困扰，直到我想到了这样的一个方法。\r\n**从成熟框架的早期源码开始看起，从作者的第一个commit开始看起，然后逐个的往前翻。这样一开始的代码量不多，多看几遍还是可以理解的。而且在这个过程中，就像电影回放一样，我们可以看到作者先写什么，后写什么，在哪些地方进行了什么样的改良，其中又不小心引入了什么bug，等等。**\r\n这真的是一个很好的办法。所以，我就用这个方法来研究vue的源码。\r\n\r\n# 目标\r\n我checkout到的版本是[这个位置](https://github.com/vuejs/vue/tree/706c67d1d013577fdbfab258bca78557419cba7c)，在这个版本中，我们可以发现：代码中主要是observer和emitter这些东西，这些是以后实现数据绑定以及$watch的关键基础。所以我们把本篇的学习目标定位为：“如何监听一个对象的变化”  具体要实现效果如下图所示。\r\n![demo](https://raw.githubusercontent.com/youngwind/blog/master/image/84/demo.gif)\r\n\r\n注：这个版本build出来的vue代码运行是会报错了，根据错误提示，很容易定位到错误原因是src/internal/init.js文件头部少引了observer和util，添加上就好了。\r\n\r\n# 思路\r\n我们有两个难点需要解决。\r\n\r\n第一：当对象的某个属性变化的时候，如何触发自定义的回调函数？\r\n答案：ES5中新添加了一个方法：[Object.defineProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty)，通过这个方法，可以自定义getter和setter函数，从而在获取对象属性和设置对象属性的时候能够执行自定义的回调函数。\r\n\r\n第二：对象往往是一个深层次的结构，对象的某个属性可能仍然是一个对象，这种情况怎么处理？\r\n比如说\r\n```js\r\nlet data = {\r\n    user: {\r\n        name: \"liangshaofeng\",\r\n        age: \"24\"\r\n    },\r\n    address: {\r\n        city: \"beijing\"\r\n    }\r\n};\r\n```\r\n答案：递归算法，也就是下面代码中的walk函数。如果对象的属性仍然是一个对象的话，那么继续new一个Observer，直到到达最底层的属性位置。\r\n\r\n下面是实现的具体代码。\r\n\r\n# 代码\r\n```js\r\n// 观察者构造函数\r\nfunction Observer(data) {\r\n    this.data = data;\r\n    this.walk(data)\r\n}\r\n\r\nlet p = Observer.prototype;\r\n\r\n// 此函数用于深层次遍历对象的各个属性\r\n// 采用的是递归的思路\r\n// 因为我们要为对象的每一个属性绑定getter和setter\r\np.walk = function (obj) {\r\n    let val;\r\n    for (let key in obj) {\r\n        // 这里为什么要用hasOwnProperty进行过滤呢？\r\n        // 因为for...in 循环会把对象原型链上的所有可枚举属性都循环出来\r\n        // 而我们想要的仅仅是这个对象本身拥有的属性，所以要这么做。\r\n        if (obj.hasOwnProperty(key)) {\r\n            val = obj[key];\r\n\r\n            // 这里进行判断，如果还没有遍历到最底层，继续new Observer\r\n            if (typeof val === 'object') {\r\n                new Observer(val);\r\n            }\r\n\r\n            this.convert(key, val);\r\n        }\r\n    }\r\n};\r\n\r\np.convert = function (key, val) {\r\n    Object.defineProperty(this.data, key, {\r\n        enumerable: true,\r\n        configurable: true,\r\n        get: function () {\r\n            console.log('你访问了' + key);\r\n            return val\r\n        },\r\n        set: function (newVal) {\r\n            console.log('你设置了' + key);\r\n            console.log('新的' + key + ' = ' + newVal)\r\n            if (newVal === val) return;\r\n            val = newVal\r\n        }\r\n    })\r\n};\r\n\r\nlet data = {\r\n    user: {\r\n        name: \"liangshaofeng\",\r\n        age: \"24\"\r\n    },\r\n    address: {\r\n        city: \"beijing\"\r\n    }\r\n};\r\n\r\nlet app = new Observer(data);\r\n```\r\n\r\n# 遗留问题\r\n上面实现的代码还有很多问题。\r\n比如：\r\n\r\n1. 只监听的对象的变化，没有处理数组的变化。\r\n2. 当你重新set的属性是对象的话，那么新set的对象里面的属性不能调用getter和setter。比如像下图所示，重新设置的job属性就不在带有自定义的getter和setter了，不再提示“你访问了job\"这些字样。\r\n![bug](https://raw.githubusercontent.com/youngwind/blog/master/image/84/bug.gif)\r\n\r\n参考资料：\r\n\r\n1. https://segmentfault.com/a/1190000004384515\r\n2. http://jiongks.name/blog/vue-code-review/\r\n\r\n"},"comment":{"url":"https://api.github.com/repos/youngwind/blog/issues/comments/256824189","html_url":"https://github.com/youngwind/blog/issues/84#issuecomment-256824189","issue_url":"https://api.github.com/repos/youngwind/blog/issues/84","id":256824189,"user":{"login":"devil5263","id":16728066,"avatar_url":"https://avatars.githubusercontent.com/u/16728066?v=3","gravatar_id":"","url":"https://api.github.com/users/devil5263","html_url":"https://github.com/devil5263","followers_url":"https://api.github.com/users/devil5263/followers","following_url":"https://api.github.com/users/devil5263/following{/other_user}","gists_url":"https://api.github.com/users/devil5263/gists{/gist_id}","starred_url":"https://api.github.com/users/devil5263/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/devil5263/subscriptions","organizations_url":"https://api.github.com/users/devil5263/orgs","repos_url":"https://api.github.com/users/devil5263/repos","events_url":"https://api.github.com/users/devil5263/events{/privacy}","received_events_url":"https://api.github.com/users/devil5263/received_events","type":"User","site_admin":false},"created_at":"2016-10-28T02:54:06Z","updated_at":"2016-10-28T02:54:06Z","body":"你好，在vue里提供了vm.$set()和Vue.set()两个方法去在更新对象属性后监听到改变，但是在单文件组件的开发方式下如何使用呢？貌似在控制台打印出this没有$set()方法，Vue根本没有"}}
{"actor":{"display_login":"devil5263"}}