1

I'm currently trying to invoke a callback based on a triggered "click" event. This approach is a hack to log out, which is only available after a click on a button.

When I do the trigger command in the console, the keyup event handler works as expected after the trigger.

Trying to automate this process with code using the following does not work however:

let editorSwitchTmce = jQuery( ".wp-editor-tabs .switch-tmce" ),
    editorCallback = function() {
    tinyMCE.activeEditor.on( "keyup", function () {
        console.log( tinyMCE.activeEditor.getContent() );
    });
};

editorSwitchTmce.bind("click", function () {
    editorCallback();
});

editorSwitchTmce.trigger( "click" );

The problem is, that the activeEditor is null until this click. So why is this not working? I mean I'm triggering the click and expecting that the activeEditor is set like when I do it with manually in the console of the browser?

8
  • Not sure I understand - are you needing to delay the call to editorCallback() when a "real click" happens? ie, to ensure that other code has time to assign the activeEditor? Commented Aug 4, 2019 at 21:41
  • The call needs to get done right after the click on the button. So when it is done u know? Commented Aug 4, 2019 at 21:43
  • ok - have you tried this? editorSwitchTmce.bind( "mouseup", .. ) Commented Aug 4, 2019 at 21:44
  • The event is not the problem i think. When I do first the trigger and add then the on keyup, everything works. Commented Aug 4, 2019 at 21:50
  • Another option might be to use a brief timeout: editorSwitchTmce.bind( "click", function () { setTimeout(function() { editorCallback(); }, 100); } ); Commented Aug 4, 2019 at 21:52

1 Answer 1

1

There a two ways this might be resolved - these depend on other constraints in your code. The preferable approach would be to call editorCallback() on mouseup:

editorSwitchTmce.bind( "mouseup", function () {
    editorCallback();
});

This assumes that other code somewhere else in your app has initialised tinyMCE.activeEditor prior to the mouseup event of that click phase.

Failing this, you could opt for editorCallback() being called after a brief timeout - the idea being that tinyMCE.activeEditor is initialised after the timeout duration lapses:

editorSwitchTmce.bind( "click", function () {
    setTimeout(function() {
        editorCallback();
    }, 100);
});

The timeout method is really a last-ditch "escape hatch" to solve this issue (ie if you're unable to correct the overall design of the app, etc). It can cause subtle system or momentary visual side effects, so use with caution.

Hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.