node.js - 在 Meteor 中重用或重新创建 react 源是否更好

标签 node.js meteor handlebars.js

我有一个名为“联系人”的模板。里面是一个#each,它呈现模板“联系人”。用户可以按“编辑”按钮,该按钮会使用已编辑行的 mongo id 设置 session 变量。然后,该行会 react 性地重新呈现为“编辑”模式。

Template.contact.viewEditing = function() {
    return Session.get("contactViewEditingId") === this._id;
}

html 多次使用 viewEditing 助手,例如:

{{#if viewEditing}}
<div class="panel-heading">EDITING!</div>
{{/if}}

我需要在 .rendered() 中绑定(bind)一些 JavaScript。我想再次检查一下我们是否正在编辑。我能想到两个选择:

  1. 我应该在 template.rendered() 中调用 Template.content.viewEditing() 吗?这会节省 react 性计算吗?
  2. 或者我应该直接复制 if 语句。此选项似乎违反了 DRY。

选项 1:

Template.contact.rendered = function() {
    if( Template.contact.viewEditing.call(this.data) ) {
        // Bind some fancy jQuery
        bindEditInPlace(this.data);
    }
}

选项 2:

Template.contact.rendered = function() {
    if( Session.get("contactViewEditingId") === this._id ) {
        // Bind some fancy jQuery
        bindEditInPlace(this.data);
    }
}

我认为在模板中多次放置 {{viewEditing}} 不会“花费”任何额外费用。所以从逻辑上讲,我认为在其他地方使用这个助手会更好。也许我需要更多帮助来理解 react 性计算。谢谢!

最佳答案

帮助程序在 Deps.Computation 内部运行,这意味着每次在帮助程序中引用和修改 react 变量时,它都会重新运行。

Template.rendered 是每次重新渲染模板时都会运行的回调(通常在模板中的辅助程序重新运行时发生),但它本身并不是响应式(Reactive)计算。

因此,使用模板助手或将其代码复制粘贴到渲染的回调中并不重要:这两种方式都不会触发响应式(Reactive)计算失效,因为我们不在其中。

就 DRY 而言,您可以像这样重构代码:

function isContactViewEditing(contactView){
    return Session.equals("contactViewEditingId",contactView._id);
}

Template.contact.helpers({
    viewEditing:isContactViewEditing
});

Template.contact.rendered=function(){
    if(isContactViewEditing(this.data)){
        //
    }
};

关于node.js - 在 Meteor 中重用或重新创建 react 源是否更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21159270/

相关文章:

javascript - 在 ember.js 中添加子路由

node.js - 图形 API - 有效的 POST 无法使用 NODE JS 工作

node.js - 快速验证、自定义异步检查

json - 公共(public)服务器上的 Git、Node.js 和 NPM

javascript - 使用 debounce 将 React 状态同步到 Meteor 集合

android - 单击时,bootstrap 单击按钮函数不执行 Meteor.call 函数(在 android 4.1.2 浏览器上)

javascript - Handlebars 包裹 &lt;!DOCTYPE html>

javascript - 循环遍历 Handlebars 中的 json 数据

node.js - Twilio 客户端错误 : Twilio IP messaging with AWS Lambda/AWS API Gateway

javascript - 无法使用 Accounts.onCreateUser 添加用户属性