官术网_书友最值得收藏!

Observables from DOM events (asEventStream)

To create an EventStream from DOM events (a mouse click for instance), we will need an HTML page with jQuery (or Zepto.js); bacon.js adds the asEventStream()method for all jQuery objects. So if we want to create an EventStream from a button click, we can use the following code:

var clickEventStream = $('#myButton').asEventStream('click'); 

This line creates an EventStream from button clicks on a DOM object with the ID myButton. If we want to execute an action every time this button is clicked, we will need to use the onValue() method from this event stream. The following code shows an alert on the screen every time the user clicks on the button:

clickEventStream.onValue(function(){ 
alert('Button clicked');
});

This code adds a function to be called every time an event happens in this EventStream object, as it emits an event every time myButton is clicked. The following code will show an alert every time this button is clicked.

As this is your first HTML code, I will paste the full HTML here so you can create a file with it and test it in your own browser:

<html> 
<head></head>
<body>
<button id="myButton">CLICK</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bacon.js/0.7.88/Bacon.min.js"></script>
<script>
var clickEventStream = $('#myButton').asEventStream('click');
clickEventStream.onValue(function(){
alert('Button clicked');
});
</script>
</body>
</html>
主站蜘蛛池模板: 措勤县| 怀宁县| 启东市| 壶关县| 渑池县| 蒲城县| 和田市| 航空| 牟定县| 伊宁市| 蓝田县| 开江县| 新乡市| 定远县| 阿巴嘎旗| 黄骅市| 拜城县| 汉中市| 遂平县| 泰和县| 图木舒克市| 宁都县| 乌兰浩特市| 牡丹江市| 寿宁县| 阳城县| 霞浦县| 多伦县| 贡觉县| 南平市| 科技| 汝城县| 光山县| 息烽县| 徐水县| 嫩江县| 日土县| 巢湖市| 岢岚县| 龙川县| 喀喇|