2012-09-21 23 views

Respuesta

9

Siguiendo la sugerencia mb21 's me las arreglé para cargar una nueva barra de herramientas de reinicializar todo el editor:

CKEDITOR.instances.editor.destroy(); 
CKEDITOR.replace('editor', configWithNewToolbar); 
3

puede volver a cargar o cambiar la barra de herramientas, sin necesidad de recargar el editor, con este código:

CKEDITOR.editor.prototype.loadToolbar = function(tbName) { 
    // If the 'themeSpace' event doesn't exist, load the toolbar plugin 
    if (!this._.events.themeSpace) { 
     CKEDITOR.plugins.registered.toolbar.init(this); 
    // causes themeSpace event to be listened to. 
    } 
    // If a different toolbar was specified use it, otherwise just reload 
    if (tbName) this.config.toolbar = tbName; 

    // themeSpace event returns a object with the toolbar HTML in it 
    var obj = this.fire('themeSpace', { space: 'top', html: '' }); 

    // Replace the toolbar HTML 
    var tbEleId = "cke_"+this.config.toolbarLocation+"_"+this.name; 
    var tbEle = document.getElementById(tbEleId); 
    tbEle.innerHTML = obj.html; 
    } // end of loadToolbar 

Al agregar la función el editor.prototype lo convierte en un método de cualquier instancia de editor. Su objeto editor probablemente sea CKEDITOR.instances.editor1

El argumento para loadToolbar es el nombre de la barra de herramientas para cargar, o si es nulo, la barra de herramientas actual se vuelve a cargar. El nombre de la barra de herramientas actual se encuentra en CKEDITOR.instances.editor1.config.toolbar. Si especifica la barra de herramientas 'foo', debe haber una matriz CKEDITOR.instances.editor1.config.toolbar_foo que defina el contenido de la barra de herramientas.

Puede agregar o quitar elementos de la matriz actual de la barra de herramientas de la variable de matrices y luego hacer que se vuelva a cargar con: edObj.loadToolbar (null);


(Meta cuestión que no afecta el método anterior: No entiendo por qué los oyentes para el evento 'themeSpace' desaparecen después de que el editor de carga originalmente el tema método (La barra de herramientas de plug-in init() hace una. event.on ("themeSpace" ...) pero las escuchas desaparecen después de que se haya inicializado el editor. No vi dónde se quitó removeListener(). Así que la llamada ... toolbar.init (this) era necesaria para restablish esos detectores de eventos por lo que la barra de herramientas podría reconstruir la nueva barra de herramientas.)

+1

.. Acerca de su último comentario, creo que el código podría utilizar algo como fireOnce por lo que los oyentes se eliminan automáticamente. – AlfonsoML

1

Sólo una rápida.

Es posible que necesite añadir esta línea a la función loadToolbar si r barra de herramientas contiene los TextColor y/o backgroundColor botones:

//Need to call init for colorbutton so that we can re-draw the color buttons 
CKEDITOR.plugins.registered.colorbutton.init(this); 
6
var editor = CKEDITOR.instances['text_id']; 
if (editor) { editor.destroy(true); } 

CKEDITOR.config.toolbar_Basic = [['Bold','Italic','Underline', 
'-','JustifyLeft','JustifyCenter','JustifyRight','-','Undo','Redo']]; 
CKEDITOR.config.toolbar = 'Basic'; 
CKEDITOR.config.width=400; 
CKEDITOR.config.height=300; 
CKEDITOR.replace('text_id', CKEDITOR.config); 
1

para mí al menos esta tiene un poco complicado ....

y para responder a la pregunta que pensé que iba a compartir el trabajo código.

tengo un fragmento de texto definido por el usuario - conocido como plantillas en el lenguaje ckeditor que necesito para cargar. También cambio dinámicamente la barra de herramientas dependiendo del ancho de la ventana, y cambia el tamaño dinámicamente en el tamaño de la ventana. cada tamaño de navegador obtiene su propia barra de herramientas personalizada. (XS, SM, MD). Espero que todos los elementos con un CKEDITOR tengan una clase de .ckeditor y que tengan una ID asignada. Además tengo un controlador de ayax para desenfocar la configuración del controlador de guardado, por lo que cuando se pierde la concentración, el control se guarda automáticamente (a través de la función ajax_post) si es necesario.

Llamo al procedimiento usando setupCKEdit. gracias a hpique por la inspiración de eliminar el objeto viejo y crear una nueva instancia. En el caso del cambio de tamaño, hago esto con un ligero retraso (resizeTimeout = 200msec), por lo que no se dispara tan seguido mientras se cambia el tamaño de la ventana.

// ********* ck editor section starts ************** 

var resizeTimeout; 
var ckeditorXSToolbar = Array(
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste','-', 'Undo', 'Redo' ] }, 
    { name: 'document', groups: [ 'mode' ], items: [ 'Source'] }, 
    { name: 'tools', items: [ 'Maximize'] }, 
    { name: 'styles', items: [ 'Format', 'Font', 'FontSize'] ,class:'hidden-xs'}, 
    { name: 'basicstyles', groups: [ 'basicstyles'], items: [ 'TextColor','Bold', 'Italic'] } 

); 

var ckeditorSMToolbar = [ 
    { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize'] ,class:'hidden-xs'}, 
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] }, 
    { name: 'editing', groups: [ 'find', 'selection' ], items: [ 'Find', 'Replace', '-', 'SelectAll' ] }, 
    { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source', '-', 'Save', 'NewPage', 'Preview', 'Print'] }, 

    { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] }, 
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'TextColor','Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] }, 
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language' ] }, 
    { name: 'tools', items: [ 'Maximize', 'ShowBlocks' ] } 
]; 
var ckeditorMDToolbar = [ 
    { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize'] ,class:'hidden-xs'}, 
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] }, 
    { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt' ] }, 
    { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source', '-', 'Save', 'NewPage', 'Preview', 'Print'] }, 

    { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] }, 
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'TextColor','Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] }, 
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language' ] }, 
    { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] }, 
    { name: 'insert', items: [ 'Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe' ] }, 

    { name: 'tools', items: [ 'Maximize', 'ShowBlocks' ] }, 
    { name: 'others', items: [ '-' ] }, 
    { name: 'about', items: [ 'About' ] } 
]; 

function setupCKEdit(selector){ 
    if (typeof(o.snippets) == 'object'){ 
     var template = { 
      imagesPath:url_img , 
      templates: o.snippets 
     }; 
     CKEDITOR.addTemplates('myTemplate', template); 
    } 
    resizeCKEdit(); 

    $('.ckeditor',selector).not('.hasCKEDITOR').each(function(index,element){ 
     $(this).addClass('hasCKEDITOR'); 
     var ckConfig = { 
      templates_replaceContent:false, 
      scayt_slang:'en_GB', 
      scayt_autoStartup:scayt_autoStartup, 
      toolbarCanCollapse:true, 
      extraPlugins:'templates,colorbutton', 
      toolbar:getCKtoolbar(), 
      toolbarStartupExpanded:getCKToolbarStartup() 
     }; 
     // inject the snippets after the toolbar[].name = 'document' 
     if (typeof(o.snippets) == 'object'){ 
      ckConfig.templates = 'myTemplate'; 
      for(var i = 0 ; i < ckConfig.toolbar.length ; i++){ 
       if (ckConfig.toolbar[i].name == 'document'){ 
        // iterate throught each document element to make sure template is not already there. 
        var hasTemplate = false; 
        for (var j = 0 ; j < ckConfig.toolbar[i].items.length; j++){ 
         if (ckConfig.toolbar[i].items[j] == 'Templates'){ 
          hasTemplate = true; 
         } 
        } 
        if (hasTemplate == false){ 
         ckConfig.toolbar[i].items.push('-'); // add to documents group. 
         ckConfig.toolbar[i].items.push('Templates'); 
        } 

       } 
      }   
     } 
     $(this).ckeditor(ckConfig); 
     var editor = CKEDITOR.instances[this.id]; 
     if(typeof(editor) == 'object'){ 
      editor.on('blur',function(event){ 
       if (event.editor.checkDirty()){ 
        var ta = $('#'+event.editor.name); // ta = textarea 
        if ((typeof(ta) == 'object') 
         && (typeof(ta[0]) == 'object') 
         && ($(ta[0]).hasClass('noajax') == false) 
         && ($(ta[0]).data('id')) 
         && (ta[0].name)) { 
         var data = { 
          field_name:ta[0].name, 
          field_value:event.editor.getData(), 
          id:$(ta[0]).data('id') 
          }; 
         data[ta[0].name]=event.editor.getData(); 
         ajax_post(url_ajax + 'update_field', data); 
         event.editor.resetDirty(); 
        } 
       } 
      }); 
     } 
    }); 
} 
function getCKtoolbar(){ 
    // returns the CK editor toolbar array based on window width 
    var dw = $(document).width(); 
    if (dw < 768){ 
     return ckeditorXSToolbar; 
    } else if(dw < 991){ 
     return ckeditorSMToolbar; 
    } 
    else { 
     return ckeditorMDToolbar; 
    } 
} 

function getCKToolbarStartup(){ 
    // returns the toolbarStartupExpanded parameter, based on window width 
    var dw = $(document).width(); 
    if (dw < 768){ 
     return false; 
    } else if(dw < 991){ 
     return true; 
    } 
    else { 
     return true; 
    } 
    return true; 
} 
function resizeCKEdit(){ 
    // when there is a document resize, update the toolbar buttons. 
    if ($('body').data('resize_enabled') == undefined){ 
     $('body').data('resize_enabled',true); 
     $(window).resize(function(event){ 
      // only do the reize 100msec after the resizing finishes. 
      window.clearTimeout(resizeTimeout); 
      resizeTimeout = window.setTimeout(function(){ 

      // iterate through all CKEDITOR instances, and update their toolbars. 
       var ckConfig = { 
        templates_replaceContent:false, 
        scayt_slang:'en_GB', 
        scayt_autoStartup:scayt_autoStartup, 
        toolbarCanCollapse:true, 
        extraPlugins:'templates,colorbutton', 
        toolbar:getCKtoolbar(), 
        toolbarStartupExpanded:getCKToolbarStartup() 
       }; 
       if (CKEDITOR.editor.length){ 
        // need to get all instances before deleting them, 
        var instances = Array(); 
        var i = 0; 
        for (var instance in CKEDITOR.instances) { 
         instances[i] = instance; 
         i++; 
        } 
        for (i = 0 ; i < instances.length ; i ++){ 
         CKEDITOR.instances[instances[i]].destroy(); 
         $('#'+instances[i]).removeClass('hasCKEDITOR'); 
         setupCKEdit($('#'+instances[i]).parent()); 
        } 
       } 
      },200); 

     }); 
    } 
} 
// ********* ck editor section ends ************** 
3

De acuerdo con [Documentación CKEditor] [1] que han renunciado al concepto de método antes mencionado 'tema' y por lo tanto el 'loadToolbar()' tienen que ser modificado un poco para trabajar con la nueva versión de CKEditor.

Esto funcionó para mí (CKEditor 4.4.4):

CKEDITOR.editor.prototype.setToolbar = function(tbName) { 
 
\t \t if (!this._.events.themeSpace) { 
 
\t \t CKEDITOR.plugins.registered.toolbar.init(this); 
 
\t \t // causes themeSpace event to be listened to. 
 
\t \t } 
 
\t \t // If a different toolbar was specified use it, otherwise just reload 
 
\t \t if (tbName){ 
 
\t \t \t this.config.toolbar = tbName; 
 
\t \t } 
 
\t \t //According to CKEditor documentation 
 
\t \t var obj = this.fire('uiSpace', { space: 'top', html: '' }).html; 
 
\t \t console.log("Received from themespace:"); 
 
\t \t console.log(obj); 
 
\t \t // Replace the toolbar HTML 
 
\t \t var tbEleId = this.id +"_" + this.config.toolbarLocation; 
 
\t \t console.log("Editor element id: " + tbEleId); 
 
\t \t var tbEle = document.getElementById(tbEleId); 
 
\t \t //tbEle.innerHTML = obj.html; 
 
\t \t $(tbEle).html(obj); 
 
     }
[1]: http://docs.ckeditor.com/#!/guide/dev_api_changes

0

Si desea una forma sencilla de cambiar las barras de herramientas en diferentes áreas, todo lo que necesita hacer es añadir el barras de herramientas a la configuración, luego seleccione la que desea cuando crea una instancia del editor.

En config.js:

CKEDITOR.editorConfig = function(config) 
{ 
// default toolbar 
config.toolbar = [ 
    { name: 'source',  items: [ 'ShowBlocks', 'Source' ] }, 
    { name: 'clipboard', items: [ 'Undo', 'Redo', '-', 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord' ] }, 
    { name: 'editing',  items: [ 'Find', 'Replace', 'SelectAll', 'Scayt' ] }, 

    { name: 'p2',   items: [ 'Blockquote', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] }, 
    { name: 'links',  items: [ 'Link', 'Unlink', 'Anchor' ] }, 
    { name: 'paragraph', items: [ 'NumberedList', 'BulletedList' ] }, 
    { name: 'insert',  items: [ 'CreatePlaceholder', 'CreateDiv', 'Image', 'Table', 'HorizontalRule', 'SpecialChar', 'Iframe' ] }, 

    //{ name: 'styles',   items: [ 'Styles', 'Format' ] }, 
    { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] }, 
    { name: 'styles',  items: [ 'Format' ] }, 
    { name: 'morestyles', items: [ 'Font', 'FontSize' ] }, 
    { name: 'colors',  items: [ 'BGColor', 'TextColor' ] } 
]; 

// here is one custom toolbar 
config.toolbar_mycustom1 = [ 
    { name: 'source',  items: [ 'ShowBlocks', 'Source' ] }, 
    { name: 'clipboard', items: [ 'Undo', 'Redo', '-', 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord' ] }, 
    { name: 'editing',  items: [ 'Find', 'Replace', 'SelectAll', 'Scayt' ] } 
]; 

// here is another custom toolbar 
config.toolbar_mycustom2 = [ 
    { name: 'styles',  items: [ 'Format' ] }, 
    { name: 'morestyles', items: [ 'Font', 'FontSize' ] }, 
    { name: 'colors',  items: [ 'BGColor', 'TextColor' ] } 
]; 

// ...other config vars here 

de la página donde se instancia una instancia editor de hacerlo de esta manera:

<script> 
    CKEDITOR.replace('MyObject', {toolbar: 'mycustom2'}); 
</script> 
1

O:

$(document).ready(function() { 
     CKEDITOR.config.customConfig = 'configSimple'; 
    }); 

    //the configSimple.js file is the same folder with config.js 
0

Te estoy asumiendo desea agregar el botón a través del archivo de complemento. Aquí es cómo. Agrega tu botón a ui.

editor.ui.addButton('ButtonName', { 
    label: lang.lockediting.locked, 
    icon: this.path + 'icons/locked.png', 
    command: 'lockediting'}); 

Luego puede presionar ButtonName a la barra de herramientas.

//Here it is pushed as a new group 
editor.config.toolbar.push(['ButtonName']); 

Si marca console.log (editor.config.toolbar); Verá la barra de herramientas como un objeto con grupos de barras de herramientas como matrices [Matriz [10], Matriz [2], Matriz [5]]. [Matriz [10] significa que hay 10 botones en el primer grupo. Puedes presionar tu botón en cualquiera de esas matrices.

0

Puede crear la barra de herramientas dinámicamente como desee. Descubrí que el mejor enfoque es escuchar eventos CKE relacionados con la creación de instancias.

CKEDITOR.on('instanceCreated', function(event) { 
    var editor = event.editor; 
    editor.config.toolbar = [ 
     { name: 'basicstyles', groups: [ 'basicstyles'], items: [ 'Bold', 'Italic','Subscript', 'Superscript' ] }, 
    ]; // could be from synchronous!!! XHR as well 
}); 

CKEDITOR.on('instanceReady', function(event) { 
    var editor = event.editor; 
    editor.config.toolbar = [ 
     { name: 'basicstyles', groups: [ 'basicstyles'], items: [ 'Bold', 'Italic','Subscript', 'Superscript' ] }, 
    ]; 
}); 
Cuestiones relacionadas