描述
它將一個(gè)事件綁定到一個(gè)對(duì)象和回調(diào)函數(shù)。 每當(dāng)一個(gè)事件觸發(fā)時(shí),它都會(huì)執(zhí)行回調(diào)。
語(yǔ)法
object.on(event, callback function, [context])
參數(shù):
event:它綁定一個(gè)對(duì)象。
callback: 它是對(duì)代碼的引用。
context: 它是一個(gè)可以傳遞給回調(diào)函數(shù)的對(duì)象。
例
<!DOCTYPE html>
<head>
<title>Event On 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:'TutorialsPoint!!!'}, Backbone.Events);
// The on() method will bind callback function to an object and invoked whenever an event triggers
myVal.on('myFunc', function () {
document.write("The triggered value is: ");
document.write(this.name);//The name will get display by referring the current object
});
//It triggers the 'myFunc' event on object 'myVal'
myVal.trigger('myFunc');
</script>
</body>
</html>
輸出
讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
- 將上面的代碼保存在on.htm文件中
- 在瀏覽器中打開(kāi)此HTML文件。
更多建議: