简体   繁体   English

Bacon.js中的惰性评估是什么?

[英]What is lazy evaluation in Bacon.js?

I am not able to understand what is lazy evaluation in Bacon.js. 我无法理解Bacon.js中的惰性评估。

I wrote the example provided by Bacon using map and flatMap and I get the same result. 我使用地图和flatMap编写了培根提供的示例,得到的结果相同。

Here is the HTML 这是HTML

<input id="itemname" type="text" />
<input id="additem" type="button" value="Add Item" />
<input id="purchase" type="button" value="Purchase" />

Here is the JS for code using map 这是使用地图的JS代码

var items = $("#additem").asEventStream("click").map(function(e){
    console.log("Executing");
    return document.getElementById("itemname").value;
}).toProperty();

var submittedItems = items.sampledBy($("#purchase").asEventStream("click"));

Here is the JS for code using flatMap 这是使用flatMap的代码的JS

var items = $("#additem").asEventStream("click").flatMap(function(e){
    console.log("Executing");
    return document.getElementById("itemname").value;
}).toProperty();

var submittedItems = items.sampledBy($("#purchase").asEventStream("click"));

For both the version of JS there is nothing logged even if I click the buttons. 对于这两个版本的JS,即使单击按钮,也不会记录任何内容。 According to documentation the second one should output "Executing" message on the console. 根据文档,第二个应在控制台上输出“正在执行”消息。

Both the code works if I attach a subscriber using onValue. 如果我使用onValue附加订阅者,则这两个代码均有效。

Please help me understand what's wrong? 请帮我了解怎么了?

When you create a stream that is based on another stream, for example by calling stream.sampledBy(...) , that does not subscribe to the original stream . 当您创建基于另一个流的stream.sampledBy(...)例如,通过调用stream.sampledBy(...) ,该stream.sampledBy(...) 订阅原始stream Regardless of how many create-stream-from-stream functions you chain together. 不管您将多少个create-stream-stream-stream函数链接在一起。 So $("#additem").asEventStream("click") does not cause a subscription, and neither does .map(...) or .toProperty(); 因此$("#additem").asEventStream("click")不会导致订阅, .map(...).toProperty();也不会导致订阅.toProperty(); .

An actual subscription is only made when calls that are specifically documented as to subscribe to the stream. 仅当明确记录为要订阅该流的呼叫时才进行实际订阅。 They are listed under "Common methods in EventStreams and Properties" here: https://baconjs.github.io/api.html - ie subscribe() , onValue() , onValues() , onError() and onEnd() . :他们是在“在EventStreams和性能的常用方法”这里列出https://baconjs.github.io/api.html -即subscribe() onValue() onValues() onError()onEnd() If you don't care about the events you could just use submittedItems.onEnd(function(){}); 如果您不关心事件,则可以使用submittedItems.onEnd(function(){}); which is never actually called since your streams never end. 由于您的流永远不会结束,因此从未真正调用过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM