BackboneJS - 事件解除



說明

此事件從物件中刪除回撥函式或所有事件。

語法

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

引數

  • event − 繫結物件。

  • callback − 指向程式碼的引用。

  • context − 可傳給回撥函式的物件。

示例

<!DOCTYPE html>
<html>
   
   <head>
      <title>Event Off 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">
         //Here creating an object 'myVal' and extending with Backbone.Events method
         var myVal = _.extend({name:'hello'}, Backbone.Events);
         
         var myFunc = function () {
            document.write('Hello');
         };
         var myFunc1 = function () {
            document.write('Welcome to TutorialsPoint');
         };

         // The on() method will bind the callback function to objects 
         // 'myFunc' and 'myFunc1'
         myVal.on('log',myFunc);
         myVal.on('log',myFunc1);
         document.write('Before using off event, values will be: ');

         // trigger() method callbacks for the given event and display the text 
         // defined in the 'myFunc' and 'myFunc1' functions
         myVal.trigger('log');

         //The off() method removes the callback for 'myFunc' and logs only 
         // text of 'myFunc1'
         myVal.off('log',myFunc);

         document.write("<br>");
         document.write('After using off event, values will be: ');
         myVal.trigger('log');
      </script>
      
   </body>
</html>

輸出

讓我們執行以下步驟來了解上述程式碼的工作原理 −

  • 將以上程式碼儲存在 off.htm 檔案中

  • 在瀏覽器中開啟此 HTML 檔案。

backbonejs_events.htm
廣告