event_suspender.js revision cedac228d2dd51db4b79ea1e72c7f249408ee061
1// Copyright 2014 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5/** 6 * @fileoverview Allows events to be suspended. 7 * 8 */ 9 10goog.provide('cvox.ChromeVoxEventSuspender'); 11 12/** 13 * @namespace 14 */ 15cvox.ChromeVoxEventSuspender = function() {}; 16 17/** 18 * A nestable variable to keep track of whether events are suspended. 19 * 20 * @type {number} 21 * @private 22 */ 23cvox.ChromeVoxEventSuspender.suspendLevel_ = 0; 24 25/** 26 * Enters a (nested) suspended state. 27 */ 28cvox.ChromeVoxEventSuspender.enterSuspendEvents = function() { 29 cvox.ChromeVoxEventSuspender.suspendLevel_ += 1; 30} 31 32/** 33 * Exits a (nested) suspended state. 34 */ 35cvox.ChromeVoxEventSuspender.exitSuspendEvents = function() { 36 cvox.ChromeVoxEventSuspender.suspendLevel_ -= 1; 37} 38 39/** 40 * Returns true if events are currently suspended. 41 * 42 * @return {boolean} True if events are suspended. 43 */ 44cvox.ChromeVoxEventSuspender.areEventsSuspended = function() { 45 return cvox.ChromeVoxEventSuspender.suspendLevel_ > 0; 46}; 47 48/** 49 * Returns a function that runs the argument with all events suspended. 50 * 51 * @param {Function} f Function to run with suspended events. 52 * @return {?} Returns a function that wraps f. 53 */ 54cvox.ChromeVoxEventSuspender.withSuspendedEvents = function(f) { 55 return function() { 56 cvox.ChromeVoxEventSuspender.enterSuspendEvents(); 57 var ret = f.apply(this, arguments); 58 cvox.ChromeVoxEventSuspender.exitSuspendEvents(); 59 return ret; 60 }; 61}; 62 63/** 64 * Returns a handler that only runs the argument if events are not suspended. 65 * 66 * @param {Function} handler Function that will be used as an event handler. 67 * @param {boolean} ret Return value if events are suspended. 68 * @return {Function} Function wrapping the handler. 69 */ 70cvox.ChromeVoxEventSuspender.makeSuspendableHandler = function(handler, ret) { 71 return function() { 72 if (cvox.ChromeVoxEventSuspender.areEventsSuspended()) { 73 return ret; 74 } 75 return handler(); 76 }; 77}; 78