Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 45 additions & 20 deletions js/mvvm.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,16 @@ function MVVM(options) {

// 数据代理
// 实现 vm.xxx -> vm._data.xxx
Object.keys(data).forEach(function(key) {
Object.keys(data).forEach(function (key) {
me._proxyData(key);
});

// 代理methods
// 实现 vm.xxx -> vm.options.methods.xxx
Object.keys(me.$options.methods).forEach(function (key) {
me._proxyAttribute(key, me.$options.methods, me)
});

this._initComputed();

observe(data, this);
Expand All @@ -18,35 +24,54 @@ function MVVM(options) {

MVVM.prototype = {
constructor: MVVM,
$watch: function(key, cb, options) {
$watch: function (key, cb, options) {
new Watcher(this, key, cb);
},

_proxyData: function(key, setter, getter) {
_proxyData: function (key, setter, getter) {
var me = this;
setter = setter ||
Object.defineProperty(me, key, {
configurable: false,
enumerable: true,
get: function proxyGetter() {
return me._data[key];
},
set: function proxySetter(newVal) {
me._data[key] = newVal;
}
});
setter = setter ||
Object.defineProperty(me, key, {
configurable: false,
enumerable: true,
get: function proxyGetter() {
return me._data[key];
},
set: function proxySetter(newVal) {
me._data[key] = newVal;
}
});
},

_initComputed: function() {
/**
*
* @param {*} key source的一个要被代理的属性名
* @param {*} source source的各个属性被代理到target
* @param {*} target target[key] 可以访问到source[key]
*/
_proxyAttribute: function (key, source, target) {
Object.defineProperty(target, key, {
configurable: false,
enumerable: false,
get: function proxyGetter() {
return source[key];
},
set: function proxySetter(newVal) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不需要set

source[key] = newVal;
}
});
},

_initComputed: function () {
var me = this;
var computed = this.$options.computed;
if (typeof computed === 'object') {
Object.keys(computed).forEach(function(key) {
Object.keys(computed).forEach(function (key) {
Object.defineProperty(me, key, {
get: typeof computed[key] === 'function'
? computed[key]
: computed[key].get,
set: function() {}
get: typeof computed[key] === 'function' ?
computed[key] :
computed[key].get,
set: function () {}
});
});
}
Expand Down