ember.js - How can I load associated records the first time they are accessed in Ember? -
i have computed property, fetches associated record , tries print it. first time fetch record, it's null. subsequent accesses work correctly. set 'async: true', setting false doesn't change behavior.
myapp.thingscontroller = ember.arraycontroller.extend({ myproperty: function() { var content = this.get('content'); return content.filter(function(thing) { console.log(thing.get('title')); // since direct attribute on model, prints fine. var associatedthing = thing.get('associatedthing'), otherthings = []; console.log(associatedthing.get('content')); // hasmany attribute on model, , null *first* time, fine on subsequent accesses. otherthings = associatedthing.get('content'); // doesn't work first time either. return thing.get('title') + otherthings[0].get('name'); // or similar. }); }.property('content.@each') // adding observers content.associatedthing.@each not seem make difference. });
models like:
myapp.thing = ds.model.extend({ title: ds.attr('string'), associatedthings: ds.hasmany('associatedthing', { async: true }) }); myapp.associatedthing = ds.model.extend({ name: ds.attr('string') });
obviously, cannot use promises here since need return value function, cannot use callback (since we're in computed property.) how can make work first time associated record accessed?
edit: myproperty computed property on arraycontroller, , used showing or hiding things
actually, can use promise, not in way you're thinking. hasmany relationships, ember-data returns promisearray. means returns promise resolve array. in meantime, proxy respond get
requests make undefined
. then, when promise resolves, observers fired. so, if have property depend on associatedthings
property, will update when promise resolves. in other words, work expected:
myapp.thing = ds.model.extend({ title: ds.attr('string'), associatedthings: ds.hasmany('associatedthing', { async: true }), sum: function() { var things = this.get('associatedthings'); return things.filter(function(thing) { return shouldfilterthing(thing); }); }.property('associatedthings.@each.size') });
also, please don't bugged fact doesn't happen synchronously. trying change asynchronous synchronous make code more fragile. let ember job , handle of properties , bindings you.
Comments
Post a Comment