Topic on Manual talk:Coding conventions/JavaScript

Place for Extensions Objects in JavaScript

3
Danwe (talkcontribs)

In many cases, if MW extensions bring some JavaScript, they create a module like object in the global scope which will hold all the extensions JS stuff, e.g. in further objects in fields of that extension object.

e.g. window.dataValues, window.dataValues.DataValue, etc.

I think there is common agreement that it is bad for extensions to pollute the global scope with those objects. Some have suggested putting those objects into the global mediaWiki object instead. This would result in mediaWiki.dataValues and mediaWiki.dataValues.DataValue etc.

I think this is equally bad. Take an extension "messages" for example. Putting it in mediaWiki.messages would overwrite the "messages" field introduced by MW core. You are simply moving the problem from global scope into the MW object and making it worse since the MW object is occupied by some stuff already. I think there should be some coding convention where to put those objects instead. In my opinion, a mw.ext would be the way to go. This would result in a mediaWiki.ext.dataValues and mediaWiki.ext.dataValues.DataValue. The slightly longer name doesn't really make it worse, and if you use it a lot in one file, you would still alias it via the files outer closure e.g.

( function( mw, dv, $, undefined ) {
	'use strict';
	// ... now you can use dv.DataValue here.
}( mediaWiki, mediaWiki.ext.dataValues, jQuery ) );
Krinkle (talkcontribs)

Per the conventions, no globals other than mw and jQuery should be used.

I agree adding third-party libraries on one of these globals directly is probably bad.

Extensions providing third-party libraries could be aliased under mw.libs if we don't want to use them directly.

As for the structure, I'd recommend this:

-- Provider
( function () {
    'use strict';

    /* local scope */

    /* public API */
    var dv = {

    };

    // Expose
    mw.dataValues = dv;
}() );

-- Consumer
( function () {
    'use strict';
    var dv = mw.dataValues;

}() );
Danwe (talkcontribs)

I agree, mw.libs should be separate. I guess we should offer a mw.ext then, so all extensions can start using that one rather than putting stuff in other places. I might upload a patch set soon, shouldn't be a big thing really.