mediawiki-extensions-Echo/modules/api/mw.echo.api.NetworkHandler.js
Matthias Mullie 876197b520 Get rid of addApiHandler factory
Some complexity is now gone. We didn't currently have a good justification
for a the APIHandler factory: the apiHandler caller would have to specify
(variable `foreign`) what kind of handler it would like to initiate anyway,
so it might as well just inject the object (which makes the code easier to
follow, decreases bugs risk because there are less code paths)

This also gives the caller more control of the API handlers:
registerForeignSources will now be able to do more. Now it can e.g. create
1 object that is shared for multiple wikis (to do lookups for multiple
wikis at once)

Also renamed addApiHandler to setApiHandler (it just sets the value it needs
without checking if it already existed anyway)

Change-Id: Ie1814c5bf1a1f0e5607033beb506df67f3585b24
2016-05-13 14:11:42 -04:00

76 lines
1.9 KiB
JavaScript

( function ( mw, $ ) {
/**
* Network handler for echo notifications. Manages multiple APIHandlers
* according to their sources.
*
* @class
*
* @constructor
*/
mw.echo.api.NetworkHandler = function MwEchoApiNetworkHandler() {
this.handlers = {};
// Add initial local handler
this.setApiHandler( 'local', new mw.echo.api.LocalAPIHandler() );
};
/* Setup */
OO.initClass( mw.echo.api.NetworkHandler );
/* Static methods */
/**
* Wait for all promises to finish either with a resolve or reject and
* return them to the caller once they do.
*
* @param {jQuery.Promise[]} promiseArray An array of promises
* @return {jQuery.Promise} A promise that resolves when all the promises
* finished with some resolution or rejection.
*/
mw.echo.api.NetworkHandler.static.waitForAllPromises = function ( promiseArray ) {
var i,
promises = promiseArray.slice( 0 ),
counter = 0,
deferred = $.Deferred(),
countPromises = function () {
counter++;
if ( counter === promises.length ) {
deferred.resolve( promises );
}
};
if ( !promiseArray.length ) {
deferred.resolve();
}
for ( i = 0; i < promises.length; i++ ) {
promises[ i ].always( countPromises );
}
return deferred.promise();
};
/* Methods */
/**
* Get the API handler that matches the symbolic name
*
* @param {string} name Symbolic name of the API handler
* @return {mw.echo.api.APIHandler|undefined} API handler, if exists
*/
mw.echo.api.NetworkHandler.prototype.getApiHandler = function ( name ) {
return this.handlers[ name ];
};
/**
* Sets an API handler by passing in an instance of an mw.echo.api.APIHandler subclass directly.
*
* @param {string} name Symbolic name
* @param {mw.echo.api.APIHandler} handler Handler object
* @throws {Error} If handler already exists
*/
mw.echo.api.NetworkHandler.prototype.setApiHandler = function ( name, handler ) {
this.handlers[ name ] = handler;
};
} )( mediaWiki, jQuery );