Ember computed properties with no dependencies

A lot of times, I have seen computed properties used in code with no dependencies specified. I wanted to understand what is the purpose of such CP’s ?

Example;

someCP: computed({
// some code
})
1 Like

It’s basically a lazily computed value that stays cached after the first time it’s needed. A computed like:

someCP: computed(function() {
  return 1 + 1;
})

Is equivalent to manually doing:

get someCP() {
  if (this._alreadyComputed != null) {
    this._alreadyComputed = 1 + 1;
  }
  return this._alreadyComputed;
}

In both cases, the actual computation only happens the first time somebody tries to use someCP.

1 Like

Thanks a lot for your reply…So when you say get someCP() {}, do you mean equivalent to a normal method call which checks if existing and does computation only _alreadyComputed is not null. I got a bit confused as you have a “get” in the front of someCP

The get is a standard Javascript feature, not an ember thing.

class Thing {
  get value() {
    return 42;
  }
}
let t = new Thing();
console.log(t.value); // prints 42;
2 Likes