BackboneJS——Event once



說明

它就像一個 **on** 事件,但會導致繫結的回撥僅在刪除之前觸發一次。

語法

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

引數

  • event——它繫結一個物件。

  • callback——它引用程式碼。

  • context——它是可以傳遞給回撥函式的物件。

示例

<!DOCTYPE html>
<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:'TutorialsPoint!!!'}, 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 檔案。

backbonejs_events.htm
廣告