Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a computed, filtered property?

Tags:

ember.js

I've got something like this:

Epic = Ember.Object.extend({
    children:[],
    children_filtered: function(){        
        return this.get("children").filterProperty("archived",false);
    }.property("children"),
    init: function() {
      this._super();
      this.set("children", Ember.ArrayController.create({content:[]}) );
      this.set("stories",  Ember.ArrayController.create({content:[]}) );
    },
});

Note the children_filtered computed property.

If I use children_filtered in a view...

{{#each content.children_filtered }}
  hi
{{/each}}

My application hangs with cpu @ 100%

Any ideas what I'm doing wrong? Is there a better pattern to follow for an object that has a list of items plus a list of filtered items?

like image 685
Marc Hughes Avatar asked Jan 15 '12 17:01

Marc Hughes


People also ask

What is the difference between a method and a computed property?

Instead of a computed property, we can define the same function as a method. For the end result, the two approaches are indeed exactly the same. However, the difference is that computed properties are cached based on their reactive dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed.

What is a computed property in a getter?

A computed property will only re-evaluate when some of its reactive dependencies have changed. This means as long as author.books has not changed, multiple access to publishedBooksMessage will immediately return the previously computed result without having to run the getter function again.

How do I create a writeable computed property?

In the rare cases where you need a "writable" computed property, you can create one by providing both a getter and a setter: Now when you run this.fullName = 'John Doe', the setter will be invoked and this.firstName and this.lastName will be updated accordingly.

What is a computed property in JavaScript?

Think of a computed property as declaratively describing how to derive a value based on other values - its only responsibility should be computing and returning that value. Later in the guide we will discuss how we can perform side effects in reaction to state changes with watchers. The returned value from a computed property is derived state.


1 Answers

Your problem is that you need the computed property to be set as cacheable. Otherwise, its value is recomputed upon every iteration of the #each. There has been discussion about whether cacheable should be the default for all computed properties.

children_filtered: function(){        
  return this.get("children").filterProperty("archived",false);
}.property("children").cacheable()

Here's a jsFiddle example: http://jsfiddle.net/ebryn/9ZKSY/

like image 60
ebryn Avatar answered Jan 06 '23 11:01

ebryn