本文概述
事件一次方法类似于方法上的事件,但是它使绑定的回调仅在被删除之前触发一次。
句法:
object.once(event, callback function, [context])
参数说明
事件:用于绑定对象。
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">
//The created object 'myVal' is extended using Backbone.Events method
var myVal = _.extend({name:'srcmini'}, 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>
输出:
将上面的代码保存在Once.html文件中,然后在浏览器中打开此文件。
评论前必须登录!
注册