Add times parameter to addOnceHandler.

This commit is contained in:
Antoine Vandecreme 2016-03-22 13:54:35 -04:00
parent fddf0fb938
commit 0f82eed0db
2 changed files with 39 additions and 3 deletions

View File

@ -57,18 +57,26 @@ $.EventSource = function() {
$.EventSource.prototype = { $.EventSource.prototype = {
/** /**
* Add an event handler to be triggered only once for a given event. * Add an event handler to be triggered only once (or a given number of times)
* for a given event.
* @function * @function
* @param {String} eventName - Name of event to register. * @param {String} eventName - Name of event to register.
* @param {OpenSeadragon.EventHandler} handler - Function to call when event * @param {OpenSeadragon.EventHandler} handler - Function to call when event
* is triggered. * is triggered.
* @param {Object} [userData=null] - Arbitrary object to be passed unchanged * @param {Object} [userData=null] - Arbitrary object to be passed unchanged
* to the handler. * to the handler.
* @param {Number} [times=1] - The number of times to handle the event
* before removing it.
*/ */
addOnceHandler: function(eventName, handler, userData) { addOnceHandler: function(eventName, handler, userData, times) {
var self = this; var self = this;
times = times || 1;
var count = 0;
var onceHandler = function(event) { var onceHandler = function(event) {
count++;
if (count === times) {
self.removeHandler(eventName, onceHandler); self.removeHandler(eventName, onceHandler);
}
handler(event); handler(event);
}; };
this.addHandler(eventName, onceHandler, userData); this.addHandler(eventName, onceHandler, userData);

View File

@ -974,6 +974,34 @@
'Handler should still have been called once.'); 'Handler should still have been called once.');
}); });
// ----------
test('EventSource: addOnceHandler 2 times', function() {
var eventSource = new OpenSeadragon.EventSource();
var userData = 'data';
var eventData = {
foo: 1
};
var handlerCalledCount = 0;
eventSource.addOnceHandler('test-event', function(event) {
handlerCalledCount++;
strictEqual(event.foo, eventData.foo,
'Event data should be transmitted to the event.');
strictEqual(event.userData, userData,
'User data should be transmitted to the event.');
}, userData, 2);
strictEqual(0, handlerCalledCount,
'Handler should not have been called yet.');
eventSource.raiseEvent('test-event', eventData);
strictEqual(1, handlerCalledCount,
'Handler should have been called once.');
eventSource.raiseEvent('test-event', eventData);
strictEqual(2, handlerCalledCount,
'Handler should have been called twice.');
eventSource.raiseEvent('test-event', eventData);
strictEqual(2, handlerCalledCount,
'Handler should still have been called twice.');
});
// ---------- // ----------
asyncTest( 'Viewer: tile-drawing event', function () { asyncTest( 'Viewer: tile-drawing event', function () {
var tileDrawing = function ( event ) { var tileDrawing = function ( event ) {