Evan Price
Evan Price

Reputation: 33

Ember.js: Setting a computed property based on all elements in a Fixture

I am building a simple data visualization that shows the share of device type based on the total number of records. I am wondering if there is a way to compute a property based on all elements in the Fixture.

App.Devices = DS.Model.extend({
    label: DS.attr('string'),
    measure: DS.attr('number'),
    share: function() {
        //code to return measure / fixtureTotal
    }.property('measure')
});


App.Devices.FIXTURES = [
    { id: "0", label: "Computer", measure: 10 },
    { id: "1", label: "Mobile",   measure: 20 },
    { id: "2", label: "Tablet",   measure: 30 }
]                                 //  fixtureTotal = 60

So in this case "Computers" would have a (10/60) share of the total records.

Can this be accomplished with computed properties or does it require another solution? Ideally this solution would work with a fixtureAdaptor or RESTAdaptor

Thanks

Upvotes: 2

Views: 836

Answers (1)

Joaquim Rendeiro
Joaquim Rendeiro

Reputation: 1388

Seems similar to what I've seen in todomvc.com: https://github.com/addyosmani/todomvc/blob/gh-pages/architecture-examples/emberjs/js/controllers/todos_controller.js#L32

Assuming you have an ArrayController that displays all Devices, here is what I would try:

  • create a computed property on the ArrayController for Devices that computes the total, and depends on @each.measure;
  • (implying that Device would be displayed by a sub-view pointing to its own ObjectController) add needs: ['devices'] to the declaration child controller, to indicate that this controller depends on the Devices controller;
  • create a computed property on the Device controller that computes the share, and depends on measure and controllers.devices.total.

Then in the share() property function on the Device controller you can get a reference to the instance of the parent controller by using this.get('controllers.devices'), or you can even get the value of the total property directly with this.get('controllers.devices.total').


I originally started the answer with "I haven't tried it myself", but since I also wanted to see if this would work, here is a JSBin with working code: http://jsbin.com/ajoqak/12/edit (edited to make it work with a REST adapter).

Note that this assumes Ember.js 1.0.0-rc2 and a build of ember-data that I made some days ago (there are no official releases yet); the API has changed a bit from some answers/examples that I've seen using previous versions.

Upvotes: 1

Related Questions