Topic on Manual talk:Coding conventions/JavaScript

Jump to navigation Jump to search

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)

As already described in the conventions, no globals other than mediaWiki and jQuery should be used.

I agree placing it on one of these globals directly is bad.

Extensions providing third-party libraries generally alias those globals in mw.libs and use them from there. A similar thing for ext makes sense.

As for the structure, I'd recommend this:

-- Provider
( function ( mw, $ ) {
    'use strict';

    /* local scope */

    /* public API */
    var dv = {

    };

    /* expose */
    mw.ext.dataValues = dv;
}( mediaWiki, jQuery ) );

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

}( mediaWiki, jQuery ) );

Note that some extensions already do this, through mw.libs. I'd like to keep that separate, though on the other hand, that one already exists and is available today.

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.

Reply to "Place for Extensions Objects in JavaScript"