【问题标题】:Edit in place Meteor view without using Session在不使用 Session 的情况下就地编辑 Meteor 视图
【发布时间】:2014-02-12 05:08:11
【问题描述】:

我想包含一个模板(或使用助手,我不在乎),可以点击该模板进行就地编辑。此视图必须是可重用的,因此不能依赖 Session 变量或视图实例不包含的任何其他变量。

在显示模式下它看起来像这样:

<div class="editable">{{content}}</div>

当你点击它时会变成编辑模式,看起来像这样:

<input type="text" value="{{content}}" />

您可以通过按回车键或按下按钮恢复到显示模式(适当地保持其更改)。

自从我第一次尝试使用 html 以来,似乎流星并没有让这变得非常容易:

<template name="editable">
    {{#if editing}}
        <input type="text" value={{this}} />
    {{else}}
        <div class="edit-thing">{{this}}</div>
    {{/if}}
</template>

// In the appropriate display template.
{{> editable stuff}}

和js:

Template.user.stuff = "yo yo yo";

Template.editable.events({
    'click .edit-thing': function(e) {
        this.isEditing = true;
    }
});

Template.editable.helpers({
    editing: function() {
        return !!this.isEditing;
    }
});

遇到了不响应式的问题,使用 Deps 库并没有解决这个问题。 (当您单击此版本时,它不会更改,因为 this.isEditing 不是响应式的,并且不会触发 editing 帮助程序的更改。)

如果您愿意,请询问更多信息!谢谢!

【问题讨论】:

  • 这是一个经典案例,当访问 template instance in the helper functions 会使任务变得更容易和更少hacky(无需偷偷地向this.data 添加属性,这应该是 只读在created函数中)。

标签: meteor handlebars.js


【解决方案1】:

这是 Deps 的典型用例,您是否记得同时使用 dependchanged? js代码可能是这样的:

Template.editable.created = function() {
    this.data.isEditing = false;
    this.data.isEditingDep = new Deps.Dependency();
};

Template.editable.events({

    '... whatever to start edit mode ...': function(e, t) {
        t.data.isEditing = true;
        t.data.isEditingDep.changed();
    },

    '... whatever to close edit mode ...': function(e, t) {
        t.data.isEditing = false;
        t.data.isEditingDep.changed();
    },
}); 

Template.editable.editing = function() {
    this.isEditingDep.depend();
    return this.isEditing;
};

【讨论】:

  • 是的,您声明事件函数的方式与我不同。我从未有过t.data 部分,我试图使用this。另外,您将如何在模板中使用它?我对你在 createdediting 之间的区别感到困惑。
  • 啊,没关系,我查看了文档!很好的解决方案!
  • @blaineh 这将在不允许扩展原生 string 类型(最新的 Chrome 和 Firefox)的浏览器中静默失败。如果您想在created 函数中扩展this.data,请考虑使用Template.user.stuff = { value: "yo yo yo"; }
  • @musically-ut,您能否发布该信息的来源?我经常使用这种模式,并没有发现任何问题。究竟是什么会失败,为什么?
  • 嘿@HubertOG,这里有一些文档谈论他的意思(data 被读/写docs.meteor.com/#template_inst 他实际上有一个观点。我正在测试它为this._isEditing看看它是如何工作的。
猜你喜欢
  • 2017-10-17
  • 2018-07-01
  • 2016-12-18
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 2013-05-24
  • 2013-05-09
  • 1970-01-01
相关资源
最近更新 更多