meteor - 如何访问嵌套模板属性?

标签 meteor quill

我成功地使用 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>

formcreated 回调中,创建一个 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/

相关文章:

editor - 动态更改 Quill 工具栏可见性

javascript - 识别 Quill.JS 中的新行

javascript - 鹅毛笔模板气泡;溢出顶部的提示 : scroll

meteor - 在 meteor 中通过LAN开发时如何更改开发环境的ROOT_URL

javascript - 为什么单击外部时 div 不隐藏?

javascript - Meteor-AutoForm:如何根据另一个控件更新选择选项

javascript - 如何访问meteor.js中集合的元素?

javascript - 如何将现有数据读入 Quill JS

javascript - 为什么 Quill 会过滤它的内容?

mongodb - 使用 cURL 上传文件