描述
它告訴對(duì)象偵聽(tīng)另一個(gè)對(duì)象上的特定事件。 它跟蹤事件并在事件發(fā)生時(shí)提供回調(diào)函數(shù)。
語(yǔ)法
object.listenTo(other, event, callback)
參數(shù)
other:定義其他對(duì)象的名稱。
event:它綁定一個(gè)對(duì)象。
callback:它是對(duì)代碼的引用。
例
<!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 w3cschool!!!'}, 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>
輸出
讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
- 將上面的代碼保存在listento.htm文件中。
- 在瀏覽器中打開(kāi)此HTML文件。
The value is: Welcome to w3cschool!!!
更多建議: