简体   繁体   English

Ember.Object中的多个属性或单个观察者

[英]Multiple properties or single observer in Ember.Object

If I have a series of properties that rely on the same property, what is the best (maintainable, fastest, etc) way of defining them? 如果我有一系列依赖相同属性的属性,那么定义它们的最佳方式(可维护,最快等)是什么? I can think of a few: 我可以想到一些:

A. Property for each: A.每个属性:

isDraft: (->
  @get('status') is App.Status.DRAFT
).property('status')

isPublished: (->
  @get('status') is App.Status.PUBLISHED
).property('status')

isArchived: (->
  @get('status') is App.Status.ARCHIVED
).property('status')

B. Observer that sets props all at once: B.一次设置道具的观察者:

isDraft: true
isPublished: false
isArchived: false

statusDidChange: (->
  @setProperties(
    isDraft: @get('status') is App.Status.DRAFT
    isPublished: @get('status') is App.Status.PUBLISHED
    isArchived: @get('status') is App.Status.ARCHIVED
  )
).observes('status')

C. Straight-up computed props: C.整理计算道具:

isDraft:     Ember.computed.equal('status', App.Status.DRAFT)
isPublished: Ember.computed.equal('status', App.Status.PUBLISHED)
isArchived:  Ember.computed.equal('status', App.Status.ARCHIVED)

(C) definitely seems the most elegant, but I'm wondering: are there are any penalties for using three computed properties versus one observer? (C)看上去绝对是最优雅的,但是我想知道:与使用一个观察者相比,使用三个计算属性会受到任何惩罚吗? And is (C) is basically shorthand for A? (C)是A的简写吗? Any difference there? 有什么区别吗?

C is a shorthand (although a small redirection) for A. And while B may give you the same answer as A and C now, it's not always guaranteed to do that. C是A的简写(尽管重定向很小)。虽然B现在可能给您与A和C相同的答案,但并不总是保证这样做。 I would avoid B at all costs since it's very hard to tell where values are coming from. 我将不惜一切代价避免使用B,因为很难说出值的来源。 Use C if your team is comfortable with the shorthand, use A to be more explicit. 如果您的团队对速记不满意,请使用C,更明确地使用A。

But most importantly, do not worry about speed, worry about readability. 但最重要的是,不必担心速度, 不必担心可读性。 Something like this is probably the last thing you should check for performance. 这样的事情可能是您应该检查性能的最后一件事。

Also, I'm not sure if this question is acceptable for the SO rules, but I thought I'd answer anyway. 另外,我不确定该问题是否适用于SO规则,但我还是想回答。

EDIT: In regards to B not guaranteed to provide the same functionality, there's 2 parts to that. 编辑:关于B不能保证提供相同的功能,有2部分。

  1. Observers are synchronous now, but may not always be. 观察者现在是同步的,但不一定总是同步的。 Minimally you should use observesImmediately() . 至少应使用observesImmediately()
  2. Observers are always active, even if the properties aren't used. 观察者始终处于活动状态,即使未使用属性也是如此。 If you use computed properties instead, Ember makes intelligent decisions about when and when not to update them. 如果改用计算属性,则Ember会明智地决定何时以及何时不更新它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM