Every so often you have a function which you only want to run once. Oftentimes these functions are in the form of event listeners which may be difficult to manage. Of course if they were easy to manage, you'd just remove the listeners but that's a perfect world and sometimes you simply want the ability to only allow a function to be called once. Here's the JavaScript function to make that possible!
通常,您都有一个只想运行一次的功能。 这些功能通常以事件侦听器的形式出现,可能难以管理。 当然,如果它们易于管理,您只需删除监听器即可,但这是一个完美的世界,有时您只是希望仅允许一次调用一个函数的功能。 这是JavaScript函数,使之成为可能!
JavaScript (The JavaScript)
Think of this once function as a wrapper for the function you provide:
将该函数视为您提供的函数的包装器:
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
// Usage
var canOnlyFireOnce = once(function() {
console.log('Fired!');
});
canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada
The wrapping function is fired only once because a tracker variable is used to ensure the function is only executed once. Many JavaScript toolkits offer this as a feature but the code to accomplish this feat is so small that it's good to have available in the case that you can dodge a JavaScript toolkit!
包装函数仅触发一次,因为使用了跟踪器变量以确保该函数仅执行一次。 许多JavaScript工具箱都将此功能作为功能提供,但是实现这一壮举的代码非常小,以至于在可以躲避JavaScript工具箱的情况下最好使用它!