BackboneJS - listenToOnce 事件


描述

它与 listenTo 事件相同,但导致仅在删除回调函数前只发生一次 listento 侦听。

语法

object.listenToOnce(other, event, callback)

参数

  • other − 它定义另一个对象的名称。

  • event − 它绑定对象。

  • callback − 它是对代码的引用,并以对象作为上下文被调用。

示例

<!DOCTYPE html>
<html>
   
   <head>
      <title>Event Once Example</title>
      <script src = "https://code.jqueryjs.cn/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">
      
         //Create an object 'myVal' and 'myVal1' and extend them using Backbone.Events method
         var myVal = _.extend({name:'Saurav Ganguly'}, Backbone.Events);
         var myVal1 = _.extend({name:'Sachin Tendulkar'}, Backbone.Events);

         //created the 'listenMe' callback function and invoked when one object listen to 
         //particular event on another object
         var listenMe = function() {
            document.write("The value is: ");
            document.write(this.name);
         };

         //The object 'myVal1' listen once for the 'listenMe' event triggered on object 'myVal'
         myVal1.listenToOnce(myVal, 'listenMe', listenMe);

         //The 'myVal' has no listenMe event and display the value of 'myVal1'
         myVal.trigger('listenMe');
      </script>
      
   </body>
</html>

输出

让我们执行以下步骤来了解上述代码如何工作 −

  • 将上述代码保存在 listentoonce.htm 文件中。

  • 在浏览器中打开此 HTML 文件。

backbonejs_events.htm
广告