gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 00:08:25 25 4
gpt4 key购买 nike

我注意到,当一个模型实例(对象)被传递给一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com