javascript - 在 View 中访问模型实例方法 (Sails.js/EJS)

标签 javascript node.js sails.js ejs

我注意到,当一个模型实例(对象)被传递给一个 View 时,它被剥夺了所有的功能。有什么办法解决这个问题吗?

例子:

我的用户模型有一个方法 fullName,它可以智能地合并名字、姓氏和前缀。

在我的 Controller 中:

User.find().done(function(err,users){
  res.view({
    users:users
  });
});

如果我在 Controller 中循环遍历用户,我可以执行 user.fullName();

如果我在 View 中做同样的事情,我会得到一个未定义的方法错误。

我可以直接在 Controller 或 View 中访问模型属性(例如 user.firstName、user.lastName)

在其他 MVC 架构(例如 rails/zendPHP)上,我通常在模型中做这样的事情,并且可以在 View 中任何我需要的地方调用 user.fullName() ,这使我可以在整个系统中保持 DRY 和一致。

为什么这行不通,有什么办法让它行得通吗?

型号

module.exports = {
    attributes: {
        email: {
          type: 'string',
          required: true,
          unique: true,
          email: true
        },
        password: {
          type: 'string',
          required: true
        },
        firstName: {
          type: 'string',
          required: false,
          maxLength: 50,
          minLength: 2
        },
        lastName: {
          type: 'string',
          required: false,
          maxLength: 50,
          minLength: 2
        },

        // Returns full name of user (or just first / last if that's all we have)
        getFullName: function(){
          return _.str.trim((this.firstName || '') + ' ' + (this.lastName || ''));
        }
    }
}

查看

<% users.forEach(function(user){ %>
<tr>
  <td><%= user.id %></td>
  <td><%= user.email %></td>
  <td><%= user.getFullName() %></td>
  <td><%= user.status %></td>
  <td><%= user.createdAt %></td>
  <td>
    <a href="#<%= user.id %>" class="btn btn-xs icon-edit"></a>
    <a href="#<%= user.id %>" class="btn btn-xs icon-trash"></a>
  </td>
</tr>
<% }); %>

我还在循环中尝试了 console.log(user) ,在 Controller 和 View 中的循环之前尝试了 console.log(users) ,很明显,当模型传递给 View 时,方法被剥离了。我还尝试了内置方法 user.toJSON() 并且在 View 中出现未定义的方法错误,但它在 Controller 中按预期工作。

最佳答案

看起来在使用 toJSON 之前必须在数组上运行 pop() 函数。然后您将可以访问 View 中的属性方法。看看它是如何在 sails documentation 中使用的.然而,这当然会删除数组中的最后一个元素......

关于javascript - 在 View 中访问模型实例方法 (Sails.js/EJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22056533/

相关文章:

javascript - for 循环内的 Gulp 流无法正常工作

javascript - jcanvas 中第二次出现动画层问题

javascript - Google Smart Lock/Google Yolo 未返回保存的密码

javascript - 未捕获的无效字符错误 : failed to convert to blob from base64 image

sails.js - 在Sails中使用数组属性类型

javascript - 如何在 Sails js (nodejs MVC) 中使用外部 rest api

javascript - 如何使用 JustGage 按扇区显示颜色

node.js - 如何在node.js中生成随机数?

javascript - NodeJS 中的同步 less 编译

sails.js - 从模块加载器sails.js 中排除文件如何在内部使用