[[Template:catfix]] gadget improvements

Fragment of a discussion from User talk:Kephir
Jump to navigation Jump to search

It sits in MediaWiki:Gadget-legacy.js. Look for "CATFIX". It should be probably re-written and migrated to MediaWiki:Common.js. (You could have found that yourself, you know. Either scroll to the bottom of MediaWiki:Common.js or Special:Search for "CATFIX" in MediaWiki and User namespaces. The first is the more reliable.)

As for the first question, use mw.Title. A link to its documentation I have put in {{editnotice-JavaScript}} — it is lumped with the rest of ResourceLoader docs. As for the second, I think a JavaScript framework of sorts should be created for accessing languages and scripts data. I have some ideas about how to create one, but I am not going to put them into reality any time soon. Use the default script in the meantime, I guess. But when it is done, the JS could download character ranges directly from Module:scripts/data (caching them in localStorage), and then use them to perform script detection in JS. (Or we could just have WebFonts handle it…)

Keφr18:21, 7 August 2014

I made the change but it seems like it only works sometimes. Other times I get the error "mw.Title is not a constructor".

CodeCat19:02, 7 August 2014

You need to declare a dependency: use mw.loader.using(['mediawiki.Title'], function () { /* ... */ }). Use it as late as possible, but not later.

Also, too much Python? In catch(e), the e is a variable holding the error. For checking the class, you use e instanceof SyntaxError or similar. Though it tends not to be very useful. (mw.Title can throw when given invalid titles, so you better check for errors, if only to swallow them.)

Also, use A.substr(0, B.length) === B instead of A.indexOf(B) === 0. The latter is quite wasteful. (ECMAScript 6 has A.startsWith(B), but it is not supported everywhere yet, so better not to rely on it.) Similarly, this.textContent || this.innerText is superior to $(this).text().

Now excuse me, I need to get back to being retired.

Keφr19:29, 7 August 2014

I made the changes you suggested, but I'm not sure I understand how declaring dependencies works. Am I supposed to wrap the whole jQuery(document).ready(function($){ ... } in yet another function? Like this?

mw.loader.using(['mediawiki.Title'], function () { jQuery(document).ready(function($){ ... } }

I guess I just don't know enough about JS stuff to understand what I am doing. I understand the language, but not the framework.

CodeCat19:41, 7 August 2014

Exactly. Though I would do it like:

if (mw.config.get('wgNamespaceNumber') === 14) // or mw.config.get('wgNamespaceIds').category for extra readability
jQuery(document).ready(function () {
	var wrapper;
	if (!(wrapper = document.getElementById("catfix")))
		return;
	mw.loader.using(['mediawiki.Title'], function () {
		// ...
	});
});
Keφr20:17, 7 August 2014

That worked, thank you!

CodeCat20:31, 7 August 2014