disable button

by John Allan

HTML

<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/pubsubjs/1.4.2/pubsub.min.js"></script>
<a href="#" class="action-button js-action-button">Do Something</a>

<a href="#" class="action-button js-action-button-2">Do Something</a>

<p>
<a href="#" class='js-fire-event'>Fire Event</a>
</p>

CSS

.action-button {
  background: black;
  color: white;
  display: block;
  padding: 10px;
}

.action-button.re-disabled {
  background: red;
}

.action-button.re-disabled-2 {
  background: green;
}

JavaScript

var generalUtilities = {
	'disableAndWaitFor': function(selector, eventName, className) {
   	var $el, className, handlers, handler, token;
        
		$el = (selector instanceof jQuery) ? selector : $(selector);
    if (!$el || !$el.length || !eventName || !eventName.length) { return false; }
    
    className = className || 're-disabled';
    
    $el.addClass(className);
		$el.on('click.disableAndWaitFor', function (e) { 
    	e.stopImmediatePropagation(); 
    });
    
    //move new binding to first position so stopImmediatePropagation will work
    handlers = $._data($el[0], 'events')['click'];
    handler = handlers.pop();
    handlers.splice(0, 0, handler);
    
    token = PubSub.subscribe(eventName, function (e) {
			$el.removeClass(className);
      $el.off('click.disableAndWaitFor');
    	PubSub.unsubscribe(token);
    });

		return $el;

	}
};

PubSub.subscribe('uiNeedsResponse', function () {
  setTimeout(function () {
  	PubSub.publish('dataResponse');
  }, 2000);
});

$('.js-action-button').on('click', function () {
  generalUtilities.disableAndWaitFor($('.js-action-button'), 'dataResponse');
  PubSub.publish('uiNeedsResponse');
});

$('.js-action-button-2').on('click', function (e) {
  generalUtilities.disableAndWaitFor(e.target, 'dataResponse', 're-disabled-2');
  PubSub.publish('uiNeedsResponse');
});

$('.js-fire-event').on('click', function (e) {
	PubSub.publish('dataResponse');
});

PubSub.subscribe('dataResponse', function (e) {
	console.log('global saw ' + e);
});