mediawiki.jqueryMsg: Extend mw.Message with new #parseDom method
authorBartosz Dziewoński <matma.rex@gmail.com>
Tue, 3 Nov 2015 23:48:11 +0000 (00:48 +0100)
committerBartosz Dziewoński <matma.rex@gmail.com>
Thu, 19 Nov 2015 01:25:23 +0000 (01:25 +0000)
Unlike #parse, this one returns a jQuery set of DOM nodes and not a
HTML string, for two benefits:

* Allows to skip unnecessary HTML serialization and reconstruction
  when we just want to insert the message contents somewhere.

  Old way:
    $( '#foo' ).html( mw.message( 'foo' ).parse() );
  New way:
    $( '#foo' ).append( mw.message( 'foo' ).parseDom() );

  This is roughly equivalent to the old alternative:
    $( '#foo' ).msg( 'foo' );
  But that way can't be used if you start with a mw.Message object, or
  don't yet know where the elements will be inserted.

* Allows to preserve the event handlers when a function is passed as
  message parameter.

    mw.messages.set( 'foo', '[$1 Click me!]' );
    $( '#foo' ).append( mw.message( 'foo', function () {
      console.log( 'Link clicked!' );
    } ).parseDom() );

Change-Id: Ia09131c2ffc1d149ca6b1c32dcd918a539c3a719

resources/src/mediawiki/mediawiki.jqueryMsg.js

index 2fe831e..ba2b684 100644 (file)
                return messageFunction( this.key, this.parameters );
        };
 
+       /**
+        * Parse the message to DOM nodes, rather than HTML string like #parse.
+        *
+        * This method is only available when jqueryMsg is loaded.
+        *
+        * @method parseDom
+        * @member mw.Message
+        * @return {jQuery}
+        */
+       mw.Message.prototype.parseDom = ( function () {
+               var reusableParent = $( '<div>' );
+               return function () {
+                       return reusableParent.msg( this.key, this.parameters ).contents().detach();
+               };
+       } )();
+
 }( mediaWiki, jQuery ) );