How to access nested template attributes?

孤街浪徒 提交于 2019-12-03 21:08:30

Here's a pattern I use to solve this sort of problem. Define a class called Editor and a template editor. The intention is that the data context inside editor will be an instance of Editor.

function Editor() {
  this.quill = null;
}

Template.editor.rendered = function () {
  this.data.quill = new Quill(...);
}
<template name="editor">...</template>

Inside form's created callback, create an Editor and store it on the template instance. Then when you call out to the editor template, pass in the Editor instance as the data context.

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>

You can then define methods on the Editor prototype which can be called by the 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();
    // ...
  }
}

This is a nice way to abstract the details of the editor so that the form doesn't need to know about it. You can reuse the editor and if you ever want to change it, you just have to make sure getTextAsHTML works the same.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!