描述
它就像在事件上,但是導(dǎo)致綁定的回調(diào)只有在被刪除之前觸發(fā)一次。
語(yǔ)法object.once(event, callback function, [context])
參數(shù)
event:它綁定一個(gè)對(duì)象。
callback:它是對(duì)代碼的引用。
context:它是一個(gè)可以傳遞給回調(diào)函數(shù)的對(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">
//The created object 'myVal' is extended using Backbone.Events method
var myVal = _.extend({name:'w3cschool!!!'}, Backbone.Events);
//The once() method causes the bound callback to only fire once before being removed
myVal.once('hello', function () {
document.write("The value after firing once is: ");
document.write(this.name);//name will get displayed by referring the current object
});
//It triggers the 'hello' event on object 'myVal'
myVal.trigger('hello');
</script>
</body>
</html>
輸出
讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
- 將上面的代碼保存在once.htm文件中。
- 在瀏覽器中打開此HTML文件。
The value after firing once is: w3cschool!!!
更多建議: