位置:首頁 > Web開發 > BackboneJS教學 > BackboneJS事件listenToOnce

BackboneJS事件listenToOnce

它同樣就像listenTo事件,當監聽發生在回調函數被刪除之前的一次。

語法

object.listenToOnce(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:'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.html

  • 在瀏覽器中打開這個HTML文件。