当前位置:   article > 正文

jquery中的观察者_jquery 观察者

jquery 观察者

jquery中的观察者

在jquery中观察者依赖下面原理实现:

<div id="observer"></div>
<script type="text/javascript">
// 注册事件
$("#observer").on('hello', function(evt, param) {
	console.log(param);
});

// 发布事件
$("#observer").trigger('hello', ['hello world!']);
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

下面是一个简单进度条解耦范例:


<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<style type="text/css">
.content {
  border: solid 1px red;
}
.bar {
  height: 20px;
  background: yellow;
}
</style>
<div id="observer"></div>
<div class="content"> 
  <div style="width: 1px" class="bar"></div>
</div>
<div id="num">0</div>

<script type="text/javascript">

$("#observer").on('progress', function(evt, param) {
  $("#num").html(param);
});

progress();
function progress() {
  var width = $(".bar").width() / 1;
  width += 2;
  $(".bar").css('width', width + 'px');
  $("#observer").trigger('progress', [width]);
  if (width < 100) {
	setTimeout(function() {
	  progress();
	}, 300);
  }
}
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/49839
推荐阅读
相关标签
  

闽ICP备14008679号