rwatcher
codePen例子
快速上手
npm install rwatcher --save
浏览器中引用
<script src="./node_modules/rwatcher/dist/rwatcher.js"></script>
Regular组件中使用
var Regular = require('Regular');
var rwatcher = require('rwatcher');
rwatcher.install(Regular);
var App = Regular.extend({
config: function(){
var watcher = this.rwatch(this);
watcher.watch(..);
}
});
watch方法使用说明
假设有以下组件
var App = Reguar.extend({
data: {
tab: {
source: [],
current: 0
},
select: {
source: [],
current: 0
},
select1: {
source: [],
current: 0
},
headers: [],
selectSate: ''
},
config: function(){
var watcher = this.rwatch(this);
}
});
同步映射
同步映射函数的最终返回值将作为目标属性的最终值
watcher.watch('source', 'target', function(){
return 1;
})
异步映射
异步映射函数将取callback的实参作为目标属性的最终值
watcher.asyncWatch('source', 'target', function(source, target, callback){
setTimeout(function(){
callback(1);
}, 1000);
});
更新监听
在watch之后调用then方法实现更新监听,可以链式调用then,基于tapable的applyPluginsWaterfall实现,目前不支持asyncWatch方法
watcher.watch('source', 'target', function(){
return 1;
}).then(function(target, source){
return 2;
}).then(function(target, source){
})
下面的例子同样适用于asyncWatch
方法
一对一映射
watch(sourceAttr, targetAttr, rule)
sourceAttr
的变动影响targetAttr
,rule
中可依次取到两个属性的当前值,返回值将作为targetAttr
的最终值
watcher.watch('select.source', 'headers', function(source, target){
return MapSourceToHeaders(source)
});
一对多映射
watch(sourceAttr, [targetAttr1, targetAttr2....], rules)
[targetAttr1, targetAttr2....]
为sourceAttr
影响的属性集合,rules为映射规则集合,与属性集合一一对应
watcher.watch('tab.current', ['select.source', 'select1.source'], [MapSelect, MapSelect1]);
or
watcher.watch('tab.current', ['select.source', 'select1.source'], MapSelect);
多对一映射
watch([sourceAttr1, sourceAttr2...], targetAttr, rule)
[sourceAttr1, sourceAttr2...]
为共同影响targetAttr的属性集合,rule为映射规则
注:不必担心在[sourceAttr1, sourceAttr2...]
中存在多余属性从而监听多余的改变,rwatcher会分析属性间的关系,将[sourceAttr1, sourceAttr2...]
处理为更加合理的版本
watcher.watch(['select.current', 'select1.current'], 'selectSate', function(sources, target){
return CombineState(sources);
});
属性映射关系图
使用displayRelationGraph()
方法生成属性映射关系图
例子
var watcher = this.rwatch();
watcher.watch('tabState.selected', ['selectState.selected', 'selectState.source'], [...]);
watcher.watch('tabState.selected', 'title', ..);
watcher.watch(['tabState.selected', 'selectState.source'], 'tableState.columns', ..);
watcher.displayRelationGraph();
生成的关系图:
其中_medium_0表示中介节点,表示多对一关系