admin管理员组

文章数量:1356588

In Ember.js I find myself defining puted properties that look like this:

someProp: function(){
  return this.get('otherProp');
}.property('otherProp')

or

someProp: function(){
  return this.get('otherObject.prop');
}.property('otherObject.prop')

Is there a shorter way to write puted properties that follow these patterns?

In Ember.js I find myself defining puted properties that look like this:

someProp: function(){
  return this.get('otherProp');
}.property('otherProp')

or

someProp: function(){
  return this.get('otherObject.prop');
}.property('otherObject.prop')

Is there a shorter way to write puted properties that follow these patterns?

Share Improve this question edited Feb 19, 2013 at 19:09 nicholaides asked Feb 19, 2013 at 18:56 nicholaidesnicholaides 19.5k13 gold badges70 silver badges83 bronze badges 5
  • I think you meant to write return this.get(...) inside your method bodies? – mavilein Commented Feb 19, 2013 at 19:02
  • Wenn i see these examples, i ask myself what value do they provide? In those simple examples, those methods just create some sort of alias for a given property. Or did you have something more plex in mind? – mavilein Commented Feb 19, 2013 at 19:04
  • @mavilein Thanks. A habit from writing CoffeeScript... – nicholaides Commented Feb 19, 2013 at 19:10
  • @mavilein, yes, the first example is certainly an alias, which is sometimes necessary. The second example is a means of following the Law of Demeter, which you can google if you need an explanation of its value. I do appreciate the "questioning the question" approach, though-- it's a good way to get people to think about the problem harder. – nicholaides Commented Feb 19, 2013 at 19:12
  • Thanks for the keyword, something to learn again :-) – mavilein Commented Feb 19, 2013 at 19:18
Add a ment  | 

1 Answer 1

Reset to default 12

Having researched a little bit you could dry this a little up by doing the following with the help of Ember.puted.alias:

someProp: Ember.puted.alias("otherObject.prop")

You can use alias also to set this property. Given an Ember object which implements the property given above, you can do:

obj.set("someProp", "foo or whatever"); // The set will be propagated to otherObject.prop

Link to Ember Source for Ember.puted.alias


Update: Ember.puted.oneWay

Recently a new puted property shorthand (oneWay) was added to Ember, which is also feasible for this requirement. The difference is that the oneWay shorthand only works in the get case. Therefore this shorthand is faster during object creation than the more plex alias.

someProp: Ember.puted.oneWay("otherObject.prop")

Link to Ember Source for Ember.puted.oneWay

本文标签: javascriptEmberjs shorthand for common computed property patternStack Overflow