BackboneJS off事件

2018-01-04 18:05 更新

描述

此事件從對(duì)象中刪除回調(diào)函數(shù)或所有事件。

語(yǔ)法

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

參數(shù)

event:它綁定一個(gè)對(duì)象。
callback:它是對(duì)代碼的引用。
context它是一個(gè)可以傳遞給回調(diào)函數(shù)的對(duì)象。

<!DOCTYPE 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>

輸出

讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
  • 將上面的代碼保存在off.htm文件中
  • 在瀏覽器中打開此HTML文件。
Before using off event, values will be: HelloWelcome to TutorialsPoint
After using off event, values will be: Welcome to TutorialsPoint

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)