BackboneJS事件listenTo


它講述了一個物件,監聽它對另一個物件的特定事件。當事件發生時它跟蹤事件並提供回撥函式。

語法

object.listenTo(other, event, callback)

引數:

  • other: 它定義了其他物件的名稱。
  • event: 它系結物件。
  • callback: 它是參考程式碼。

範例

<!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">
     	//Create an object 'myVal' and 'myVal1' and extend them using Backbone.Events method
        var myVal = _.extend({name:'Hello..'}, Backbone.Events);
        var myVal1 = _.extend({name:'Welcome to YiiBai!!!'}, Backbone.Events);

       //create the 'listenMe' callback function and invoke when one object listens to particular event on another object
        var listenMe = function(){
           document.write("The value is: ");
           document.write(this.name);
        };
      //The object 'myVal1' listens once for the 'listenMe' event triggered on object 'myVal'
       myVal1.listenTo(myVal, 'listenMe', listenMe);

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

輸出

讓我們進行以下步驟來看看上面的程式碼工作:

  • 儲存上述程式碼在檔案listento.html

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