我成功地使用 quill wysiwyg 实现了一个表单,但现在我想创建一个组件来重用它。这是我的工作实现:
<template name="form">
<form>
<div id="toolbar"> ... html with toolbar buttons </div>
<div id="editor"></div>
<input type="submit" value="save"/>
</form>
</template>
Template.form.rendered = function () {
this.quill = new Quill('#editor', {
modules: {
'toolbar': { container: '#toolbar' },
'link-tooltip': true
},
theme: 'snow' }
);
}
Template.form.events({
'submit form': function(e, tmpl) {
e.preventDefault();
var html = tmpl.quill.getHTML();
// code to save the form data
}
这就是我想要使其可重用的。我的问题在代码中:
<template name="form">
<form>
{{> editor }}
<input type="submit" value="save"/>
</form>
</template>
<template name="editor">
<div id="toolbar"> ... html with toolbar buttons </div>
<div id="editor"></div>
</template>
Template.editor.rendered = function () {
this.quill = new Quill('#editor', {
modules: {
'toolbar': { container: '#toolbar' },
'link-tooltip': true
},
theme: 'snow' }
);
// How can I pass quill to the parent template?
}
Template.form.events({
'submit form': function(e, tmpl) {
e.preventDefault();
// How can I access quill variable on the nested template, so I can
// call quill.getHTML()?
}
最佳答案
这是我用来解决此类问题的模式。定义一个名为 Editor
的类和一个模板 editor
。其目的是 editor
内的数据上下文将是 Editor
的实例。
function Editor() {
this.quill = null;
}
Template.editor.rendered = function () {
this.data.quill = new Quill(...);
}
<template name="editor">...</template>
在 form
的 created
回调中,创建一个 Editor
并将其存储在模板实例上。然后,当您调用 editor
模板时,传入 Editor
实例作为数据上下文。
Template.form.created = function () {
this.editor = new Editor();
}
Template.form.helpers({
editorInstance: function () {
return Template.instance().editor;
}
});
<template name="form">
<form>
{{> editor editorInstance }}
<input type="submit" value="save"/>
</form>
</template>
然后,您可以在 Editor
原型(prototype)上定义可由 form
调用的方法:
Editor.prototype.getTextAsHTML = function () {
return this.quill && this.quill.getHTML();
}
Template.form.events({
"submit form": function(e, tmpl) {
e.preventDefault();
var html = tmpl.editor.getTextAsHTML();
// ...
}
}
这是抽象编辑器
详细信息的好方法,这样表单
就不需要知道它。您可以重复使用编辑器
,如果您想更改它,只需确保getTextAsHTML
的工作方式相同即可。
关于meteor - 如何访问嵌套模板属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26549964/