考虑以下 Bacon.js 代码示例(大致基于 the code here,使用 bacon.model 和 bacon.jquery):
<input id="total" type="text" placeholder="total">
/
<input id="quantity" type="text" placeholder="quantity" value="1">
=
<span id="price"></span>
<script>
var $total = Bacon.$.textFieldValue($("#total")).changes();
var quantity = Bacon.$.textFieldValue($("#quantity"));
var price = Bacon.when(
[$total, quantity], function(x,y) { return x/y; }
).toProperty(0);
price.onValue(function (p) {
$('#price').text(p);
});
</script>
这里发生的是流 $total
和属性 quantity
被连接到属性 price
中。 $total
和 quantity
都从文本输入字段中获取输入,但只有 $total
提示 price
更新。 (即 quantity
被采样但不是同步模式的一部分。)
我正在尝试使用 RxJS 而不是 Bacon.js 来实现同样的行为,但我所能想到的只是 super 丑陋的解决方案。我想我一定是忽略了什么……?
到目前为止我最好的镜头(行为不尽相同,但你明白了):
var totalChange = Rx.Observable.fromEvent($('#total'), 'input');
var totalValue = totalChange.map(function () {
return parseInt($('#total').val(), 10);
});
var quantityValue = totalChange.map(function () {
return parseInt($('#quantity').val(), 10);
});
var price = Rx.Observable.zip(
totalValue,
quantityValue,
function (x,y) {
return x/y;
}
);
price.subscribe(function (p) {
$('#price').text(p);
});
因为 combineLatest
或 zip
都没有在直接表示两个文本字段的可观察对象上提供所需的行为,所以我能想到的就是创建一个基于数量的可观察对象在总计文本字段中输入事件。哪个可行,但感觉很牵强。
对替代方法有什么建议吗?
最佳答案
使用最近添加的withLatestFrom
而不是 combineLatest
。
var price = totalValue.withLatestFrom(quantityValue, (x,y) => x/y);
比较他们的图表:
关于javascript - RxJS 等效于 `Bacon.when()` 具有属性(被采样但不是同步模式的一部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28153548/