BackboneJS 单次监听器

2018-01-04 18:22 更新

描述

它就像在事件上,但是导致绑定的回调只有在被删除之前触发一次。

语法
object.once(event, callback function, [context])

参数

event:它绑定一个对象。
callback:它是对代码的引用。
context:它是一个可以传递给回调函数的对象。
<!DOCTYPE html>
  <head>
    <title>Event Once Example</title>
      <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script>
  </head>
  <body>
     <script type="text/javascript">

     	//The created object 'myVal' is extended using Backbone.Events method
        var myVal = _.extend({name:'w3cschool!!!'}, Backbone.Events);

        //The once() method causes the bound callback to only fire once before being removed
        myVal.once('hello', function () {
           document.write("The value after firing once is: ");
           document.write(this.name);//name will get displayed by referring the current object
        });

        //It triggers the 'hello' event on object 'myVal'
        myVal.trigger('hello');
     </script>
  </body>
</html>

输出

让我们执行以下步骤,看看上面的代码如何工作:
  • 将上面的代码保存在once.htm文件中。
  • 在浏览器中打开此HTML文件。
The value after firing once is: w3cschool!!!

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号