Skip to content

Commit

Permalink
feat: 为computed属性增加getter和setter
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhan committed Aug 10, 2021
1 parent 9b8017f commit 4a7abfb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
16 changes: 16 additions & 0 deletions src/runtime/data.js
Expand Up @@ -177,6 +177,17 @@ function immutableSet(source, exprPaths, pathsStart, pathsLen, value, data) {
return result;
}

/**
* 检查是否是在更新computed的数据
*
* @param {string} prop 数据项路径
* @param {*} value 数据值
* @return {boolean} 是否执行了computed的setter
*/
Data.prototype._updateComputed = function (prop, value) {
return this.__computed && this.__computed[prop] && (this.__computed[prop](value) || 1);
};

/**
* 设置数据项
*
Expand Down Expand Up @@ -210,6 +221,11 @@ Data.prototype.set = function (expr, value, option) {
};

var prop = expr.paths[0].value;

if (!option.__forceComputed && this._updateComputed(prop, value)) {
return;
}

this.raw[prop] = immutableSet(this.raw[prop], expr.paths, 1, expr.paths.length, value, this);

this.fire({
Expand Down
12 changes: 10 additions & 2 deletions src/view/component.js
Expand Up @@ -491,7 +491,7 @@ Component.prototype._calcComputed = function (computedExpr) {

var me = this;
try {
var result = this.computed[computedExpr].call({
var result = (this.computed[computedExpr].get || this.computed[computedExpr]).call({
data: {
get: function (expr) {
// #[begin] error
Expand All @@ -516,11 +516,19 @@ Component.prototype._calcComputed = function (computedExpr) {
}
}
});
this.data.set(computedExpr, result);
this.data.set(computedExpr, result, {
// 添加一个flag,避免死循环
__forceComputed: 1
});
}
catch (e) {
handleError(e, this, 'computed:' + computedExpr);
}
// 如果computed是对象且存在set方法
if (this.computed[computedExpr].set) {
this.data.__computed = this.data.__computed || {};
this.data.__computed[computedExpr] = bind(this.computed[computedExpr].set, this);
}
};

/**
Expand Down

0 comments on commit 4a7abfb

Please sign in to comment.