středa 18. dubna 2012

Setting "blockNodeForEnter" for EnterKeyHandling plugin of Dijit/Editor

You might run into a problem when you would like to change default behaviour of Dijit Editor. By default, when user presses enter key in Dijit Editor, only <br /> tag is generated. What if you want to encapsulate text into <p> tags or <div> tags?


Writing post filter was not helpful (probably because EnterKeyHandling plugin processing was fired after post filter, but I am not sure about this). So I opened /dijit/_editor/plugins/EnterKeyHandling.js and the solution was right in front of me:
// This plugin has three modes:
//
// * blockNodeForEnter=BR
// * blockNodeForEnter=DIV
// * blockNodeForEnter=P
//
// In blockNodeForEnter=P, the ENTER key starts a new
// paragraph, and shift-ENTER starts a new line in the current paragraph.
Now the only problem: How to change default mode from BR to P? Where can it be done?


Constructor of EnterKeyHandling states:

if("blockNodeForEnter" in args){
args.blockNodeForEnter = args.blockNodeForEnter.toUpperCase();
}
We are close to finish! How to pass custom args when invoking this plugin? The Dijit Editor has array "plugins" in which are stored all plugins for editor. Invocation of these plugins is done in "addPlugin" method.


The magic is done on this line:
var args=lang.isString(plugin)?{name:plugin}:lang.isFunction(plugin)?{ctor:plugin}:plugin;
This line can be translated as: if passed plugin is string, us it as plugin name (for plugins like "bold", "italic" etc.). If passed plugin is function, it is considered to be dojo Class and is used as constructor ({ctor:plugin} part). And anything else is just passed as is.
The args variable is passed to plugin constructor few lines later. 


So! We can add custom object to plugins array of editor that will look somehow like this:

{
ctor: EnterKeyHandlingPlugin,
blockNodeForEnter: 'P'
}
Easy huh? Very unfortunate that this is undocumented or not easy to find :/
Complete example:


require([
"dijit/Editor",
"dijit/_editor/plugins/EnterKeyHandling",
        "dijit/_editor/plugins/LinkDialog",
        "dijit/_editor/plugins/FullScreen"
], function( DijitEditor, DijitEditorEnterKeyHandling) {
var editorConfig = {
plugins: [
"bold",
"italic",
"|",
"cut",
"copy",
"paste",
"|",
"createLink",
"fullscreen",
{
ctor: DijitEditorEnterKeyHandling,
blockNodeForEnter: 'P'
}
]
};
var editor = new DijitEditor(editorConfig);
}); 



2 komentáře:

  1. Thank you very much for sharing! The default behaviour in my installation was 'P' and I had to change it to 'BR'.

    Best regards,
    Harald

    OdpovědětVymazat