【问题标题】:Dynamically insert template into table row将模板动态插入表格行
【发布时间】:2013-06-12 12:29:51
【问题描述】:

我有一个表格,其中包含来自集合的数据。当用户单击一行时,我想用表单替换该行的内容以编辑内容。如果可能的话,如果没有 jQuery,流星的方式会是什么?

<template name="table">
  <table>
    {{#each items}}
    {{> showrow}}
    {{else}}
  </table>
</template>

<template name="showrow">
  <tr>
    <td>{{name}}</td>
  </tr>
</template>

<template name="editrow">
  <tr>
    <form>
      … form html …
    </form>
  </tr>
</template>

我认为,基本上,这是关于用editrow 替换showrowtemplate for onw 行。这是一个合理的方法吗?有什么指点吗?

【问题讨论】:

标签: meteor


【解决方案1】:

你可以使用逻辑助手

<template name="table">
  <table>
    {{#each items}}
        {{#if editmode}}
            {{>editrow}}
        {{else}}        
            {{> showrow}}
        {{/if}}
    {{/each}}         
  </table>
</template>

然后在你的模板助手中

Template.table.editrow = function() {
    return (this.editmode)
}

this 允许您访问循环中特定项目的集合中的数据上下文。因此,如果您对该项目有 editmode:true,它将改用编辑行。

【讨论】:

  • 另外,您可以有一个会话变量来跟踪当前正在编辑的项目。然后你可以做类似return Session.get('editingItemId') === this._id 的事情。然后,您需要在 created 和离开编辑模式时将会话变量设置为 null
  • 谢谢。 @Akshat,如果我更改项目中的编辑模式,会自动更改显示吗?
  • 我宁愿将正在编辑的项目放入会话变量中,这对我来说更有意义,尤其是对于多个用户而言。
  • 是的,它也会是反应式的,所以如果你改变编辑模式,它就会这样做。这取决于你希望你的逻辑如何工作,上面只是一个例子。如果你想按下某个东西使其可编辑,使用 Session 会很有效,如果你想按下另一个东西是可编辑的
【解决方案2】:

好的,这比预期的要容易。流星 1:0:

我在数据属性中使用 MongoDB _id 作为每一行的标识符:data-id="{{_id}}"

然后我在&lt;tr&gt;-elements 上设置了一个click 事件处理程序:

Template.booking.events({
    'click tr': function(event, template) {
        Session.set(editBookingId, event.currentTarget.getAttribute('data-id'));
    }
});

模板助手监听传入的 id 并在 id 匹配时返回 true:

Template.booking.helpers({
    'isEdited': function(id) {
        return Session.get(editBookingId) == id;
    }
});

在模板中,我用{{#if}} 决定是显示普通行还是编辑对话框:

{{#if isEdited _id}}EDIT{{/if}}

很少的代码。非常好。谢谢指点。

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 2011-02-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多