应该在模型或控制器中声明一个计算属性? [英] should a computed property be declared in a model or controller?

查看:89
本文介绍了应该在模型或控制器中声明一个计算属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拥有以下用户模型:

Sks.User = DS.Model.extend
  firstName: DS.attr("string")
  lastName: DS.attr("string")

其中应该声明'fullName'计算属性吗?

where should the 'fullName' computed property be declared?

  fullName: Ember.computed(->
    firstName = @get("firstName")
    lastName = @get("lastName")
    firstName = ""  if firstName is `undefined`
    lastName = ""  if lastName is `undefined`
    lastName + " " + firstName
  ).property("firstName", "lastName")

应该在UsersController还是直接在模型中? Ember文档说,仅在会话中使用的字段应该写在控制器中。但问题是我无法在索引模板中访问fullName:

Should it be in 'UsersController' or directly in the model? The Ember documentation says that fields used only across session, should be written in controllers. But the problem is I couldn't access 'fullName' in the Index template:

Sks.IndexController = Ember.Controller.extend
  needs: ['users']

这里,'fullName'无法访问控制器)

Here, 'fullName' was inaccessible (declared in the controller)

{{#each user in controllers.users}}
  <li>{{user.fullName}}</li>
{{/each}}

但是它是在模型中的。 / p>

But it is when it is in the model.

推荐答案

在这种情况下,我认为该模型是计算属性的正确位置,因为只有具有第一个名称和lastname属性。

In this case I think the model is the right place for the computed property because it only makes sense if you have the firstname and lastname attributes.

当控件有意义时,您仍然可以将计算机属性放在控制器上,但是我想像一个像fullName这样的属性可以在不止一个地方使用您的应用程序(并在控制器中使用此功能将强制您复制应用程序不同部分的工作)

You can still put computed properties on the controller when it makes sense, but I imagine a property like "fullName" could be used in more than one place across your application (and having this in the controller would force you to duplicate the effort across different parts of the app)

这篇关于应该在模型或控制器中声明一个计算属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆