我目前正在测试新的Gutenberg用户界面,我对一些旧代码有一些疑问。
我希望在元数据库中更改metabox值时更新按钮(在我的情况下是一个tinymce编辑器,但我对隐藏输入有同样的问题)
// here is the part of code for the tynimce editor
tc.setup = function (ed) {
ed.on('blur', function (e) {
// generate data when cursor move out
ed.save();
console.log('i want to change update button state :\')');
// this not work...
// $('#my-hidden-input-or-textarea')
// .val(new Date().getMilliseconds())
// .trigger("change")
// .trigger('click');
});
};
tinymce.init(tc);
答案 0 :(得分:1)
jQuery不会触发真正的DOM事件,但会尝试在自己的内部事件映射中查找回调 https://github.com/facebook/react/issues/3249#issuecomment-77814784
另见:https://github.com/WordPress/gutenberg/issues/3975
所以灵魂就是通过vanilla Javascript触发事件,如:
<script type="text/javascript">
// listen on metaboxes form
jQuery(document).on('input-dirty', '.editor-meta-boxes-area form', function () {
var $ = jQuery;
var element = $(this)[0];
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
} else {
element.fireEvent("onchange");
}
});
// trigger event programmatically changed element
$('.your-input').closest('form').trigger('input-dirty');
</script>
对于tinymce编辑:
<?php
// or for custom tinymce editor
$options['tinymce']['setup'] = "function (ed) {
ed.on('blur', function (e) { // generate the content and set textarea on blur
ed.save();
// fix for gutenberg editor, trigger change on programmatically changed input
$(ed.getElement()).closest('form').trigger('input-dirty');
});
}";
$options = array_merge(array('media_buttons' => true, 'textarea_rows' => 16, 'teeny' => true, 'quicktags' => true, 'textarea_name' => $id), $options);
wp_editor($input_text_content, $id . '_' . rand(100, 9999), $options);
?>