数值-Value

这是一个multicast的实例,可以订阅一个数字的变化

引入

import { value } from 'popmotion';

使用

value(initialValue, onUpdate);
import { tween, value } from 'popmotion';
import styler from 'stylefire';

const div = styler(document.querySelector('div'));
const divX = value(0, div.set('x'));

tween({ to: 500 }).start(divX);

setTimeout(() => console.log(() => {
  physics({
    velocity: divX.getVelocity()
  }).start(divX); // This will automatically `stop` the tween
}), 150);

上面的例子分两步:

  1. 150ms之前执行tween动画,每一帧都会调用divX.update,然后div的位置会被改变
  2. 150ms之后,tween动作会被停止,执行physics动画,div的位置将由physics动画来改变

value也可以通过数组和对象初始化

const foo = value({ x: 0, y: 0 });
const bar = value([0, 0]);

foo.getVelocity(); // { x: 0, y: 0 }
bar.getVelocity(); // [0, 0]

作为一个multicast类型的反馈,你可以订阅更多的反馈动作

const foo = value(0);
foo.subscribe(() => console.log('first reaction'));
foo.subscribe(() => console.log('second reaction'));

方法

  • get():number:返回当前的值
  • getVelocity():number:返回当前值的变化速度(变化速度可以理解为,上一帧跟这一帧的时间内,数值变化了多少,变化越快,速度越大)
  • subscribe:同multicast
  • filter:同action
  • pipe:同action
  • while:同action
  • stop:同action

实例方法

unsubscribe