TinyMCE: How bind on event after its initialized

前端 未结 5 1520
轮回少年
轮回少年 2021-01-11 14:16

I already searched a lot but by google-fu\'ing don\'t get me any results :(

I have an already initialized tinyMCE editor which initiali

5条回答
  •  星月不相逢
    2021-01-11 15:13

    EDIT: oops - I thought this was another question I was looking at that was specific to WordPress + TinyMCE, guess not. Though I'll leave the answer here as it may be helpful to others.

    The proper way to do this would be to append to the tinyMCE init with the WordPress filter. For example:

    PHP (in functions.php or other location that is run on edit page load):

      add_action( 'init', 'register_scripts' );     
      function register_scripts(){
        if ( is_admin() ) {
          wp_register_script(
            'admin-script',
            get_stylesheet_directory_uri() . "/js/admin/admin.js",
            array('jquery'),
            false,
            true
          );
        }
      }
    
      add_action( 'admin_enqueue_scripts', 'print_admin_scripts' );
      function print_admin_scripts() {        
        wp_enqueue_script('admin-script');
      }
    
      add_filter( 'tiny_mce_before_init', 'my_tinymce_setup_function' );
      function my_tinymce_setup_function( $initArray ) {
        $initArray['setup'] = 'function(ed){
          ed.onChange.add(function(ed, l) {
            tinyOnChange(ed,l);
          });
        }';
        return $initArray;
      }
    

    JavaScript (/js/admin/admin.js)

      (function($){
        window.tinyOnChange = function(ed, l){        
          console.log('Editor contents was modified. Contents: ' + l.content);      
        }
      }(jQuery);
    

    This is tested and working in WordPress 3.9 (though I am simply getting the console output:

    Deprecated TinyMCE API call: .onChange.add(..) 
    

    But that's due to tinyMCE deprecating code you're trying to use. This method does still work to modify to any of the tinyMCE init options - I'm currently using it for init_instance_callback and it's working great.

    -Thomas

提交回复
热议问题