Recognize when loading of hasMany relationship is finished - ember.js

I've got two models, connected with a async hasMany relationship:
App.Car = DS.Model.extend({
model: DS.attr('string'),
passengers: DS.hasMany('passenger', { async: true }
});
and
App.Passenger = DS.Model.extend({
name: DS.attr('string')
});
How can I observe the loading status of a cars passenger? I tried:
App.CarPassengerController = Em.ObjectController.extend({
needs: ['cars'],
carsBinding: 'controllers.cars',
loadObserver: function() {
console.log('passengers loading status of changed');
}.observes('cars.#each.passengers.isFulfilled')
});
This doesn't work, as the observer is only fired after the cars are loaded, but not after the promises are fulfilled. (I know they are fulfilled, because this is indicated in the Ember Inspector.)
Has anyone experienced a similar problem and found a solution for it? Thanks!

There's gotta be a better way than this (and I'd be interested in knowing too), but this is how I've been doing it (hacking it, really) so far:
setupController: function(controller, model) {
this._super(controller, model);
var cars = model.get('cars')
var carCount = cars.get('length')
var carIterator = 0
cars.forEach(function(car){
car.get('passengers').then(function(passengers){
carIterator++;
if(carIterator == carCount) {
// all passengers from all cars have been loaded
controller.set('passengers_loaded', true)
}
})
})
}

Related

Ember-Data store.filter with async relationships

I am working on a survey application and we are using an existing API. Our models look like:
App.User = DS.Model.extend({
name: DS.attr('string'),
participations: DS.hasMany('participation', {async: true})
});
App.Participation = DS.Model.extend({
user: DS.belongsTo('user', {async: true}),
survey: DS.belongsTo('survey', {async: true}),
hasCompleted: DS.attr('boolean'),
hasAccepted: DS.attr('boolean')
});
App.Survey = DS.Model.extend({
participations: DS.hasMany('participation', {async: true}),
title: DS.attr('string'),
locked: DS.attr('boolean')
});
I would like to return a live record array from my model hook via store.filter however this filter needs to deal with both survey's and the async participant record for the current user. How can I handle the async relation resolution in my filter callback function?
model: function() {
return Ember.RSVP.hash({
user: this.store.find('user', 1),
surveys: this.store.filter('survey', {}, function(survey) {
return !survey.get('locked'); //How do I get the participation record for the current user for the current poll so I can also filter out the completed true
})
});
}
If using a live record array of survey's is not the best way to deal with this what is?
Edit:
I've updated the approach to try:
App.SurveysRoute = Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
user: this.store.find('user', 1),
all: this.store.find('survey'),
locked: this.store.filter('survey', function(survey) {
return survey.get('locked');
}),
completed: this.store.filter('participation', {user: 1}, function(participation) {
return participation.get('hasCompleted');
}),
outstanding: this.store.filter('participation', {user: 1}, function(participation) {
return !participation.get('hasCompleted') && !participation.get('poll.locked');
})
});
}
});
App.SurveysCompletedRoute = Ember.Route.extend({
model: function() {
return this.modelFor('surveys').completed.mapBy('survey');
}
});
http://jsbin.com/vowuvo/3/edit?html,js,output
However, does the usage of the async property participation.get('poll.locked') in my filter pose a potential problem?
Had originally written my response in ES6 and ember-cli format, while localising Ember references... please excuse if this is a touch basic as I reverted it to ES5 and used commonly understood code structure for Ember.
Try this:
// beforeModel() and model() are skipped if coming from a collection
// ie: from '/users' to '/users/1'
// setting this up is purely for direct linking to this route's path.
model: function(params) {
return this.store.findRecord('user', params.id).then(function(user) {
return user.get('participations');
});
},
// only fired once!
// soon to be obsolete...
setupController: function(controller, model) {
controller.set('model', model);
var store = this.store,
userId, availSurveys, completed, outstanding;
store = this.store;
userId = model.get('id');
// this is a promise!
// also, these filters can be applied elsewhere that Store is available!
availSurveys = store.filter(
// modelName to be filtered.
'surveys',
// this part is the query - sent as a request to server, not used as a filter
{ locked: false },
// this is the active filter that will be applied to all survey records in client,
// updating 'availSurveys' as the records change
function(survey) {
return !survey.get('locked');
});
completed = store.filter('participation',
{
user : userId,
hasCompleted : true
},
function(participation) {
return participation.get('hasCompleted');
});
outstanding = store.filter('participation',
{
user : userId,
hasCompleted : false,
survey : { locked: false }
},
function(participation) {
// this is also a promise!
return participation.get('survey').then(function(survery) {
return !participation.get('hasCompleted') && !survey.get('locked');
});
});
// alternatively, hashSettled waits until all promises in hash have resolved before continuing
Ember.RSVP.hash({
availSurveys : availSurveys,
completed : completed,
outstanding : outstanding
}).then(function(hash) {
controller.set('availSurveys', hash.availSurveys);
controller.set('completed', hash.completed);
controller.set('outstanding', hash.outstanding);
});
}

Emberjs promiseArray inside route doesn't return properly

I have a controller for showing item.
Users can put the item in their wish list.
(Item has many users, User has many Items.)
So, when user enter the webpage, I want to show a AddToList or RemoveFromList button to the user based on isAddedToList property.
Below is the code.
User Model:
var User = DS.Model.extend({
username: DS.attr('string'),
email: DS.attr('string'),
avatar: DS.attr('string'),
items: DS.hasMany("item", { async: true })
});
export default User;
ItemModel:
var Item = DS.Model.extend({
name: DS.attr("string"),
priceInCent: DS.attr("number"),
salePriceInCent: DS.attr("number"),
brand: DS.belongsTo("brand"),
itemImages: DS.hasMany("itemImage", { async: true }),
users: DS.hasMany("user", { async: true }),
});
export default Item;
ItemRoute:
var ItemRoute = Ember.Route.extend({
model: function(params) {
var userId = this.get("session").get("userId");
return Ember.RSVP.hash({
item: this.store.find('item', params.item_id),
user: this.store.find('user', userId),
});
},
setupController: function(controller, model) {
controller.set('item', model.item);
controller.set('user', model.user);
}
});
export default ItemRoute;
ItemController:
var ItemController = Ember.Controller.extend({
needs: ["current-user", "application"],
currentUser: Ember.computed.alias("controllers.current-user"),
isAddedToList: function() {
var promiseUsers = this.get("item.users"), user = this.get("user");
return promiseUsers.contains(user);
}.property("item"),
actions: {
addToList: function() {
var item = this.get("item"), user = this.get("user");
item.get("users").pushObject(user);
item.set("addedUserIds", [user.get("id")]);
item.save();
},
removeFromList: function() {
var item = this.get("item"), user = this.get("user");
item.get("users").removeObject(user);
item.set("removedUserIds", [user.get("id")]);
item.save();
}
}
});
export default ItemController;
The problem is when I check the length of promiseUsers with
promiseUsers.get("length")
it always returns 0.
but when I try the same with Chrome console, it returns the length properly.
Do I miss something in the route? How to fix the problem?
The problem is you're using your code synchronously, despite it being an asynchronous property.
The first time you attempt to use an async relationship it will begin resolving the relationship, making a callback to the server is necessary. In your case you try to use the users right away, but they are going to be empty the first time, so you're contains will return false. Since you aren't watching the users' collection it will then update, but the computed property won't update since the computed property was just watching item. This is why when you try it from the console it works, because by the time you attempt to use it in the console it's finished resolving the async collection of users.
isAddedToList: function() {
var promiseUsers = this.get("item.users"), user = this.get("user");
return promiseUsers.contains(user);
}.property("user", 'item.users.[]')

Implementing model filter

I have set up the following scaffolding for my Ember application.
window.App = Ember.Application.create({});
App.Router.map(function () {
this.resource('coaches', function() {
this.resource('coach', {path: "/:person_id"});
});
});
App.ApplicationAdapter = DS.FixtureAdapter.extend({});
App.Person = DS.Model.extend({
fname: DS.attr('string')
,lname: DS.attr('string')
,sport: DS.attr('string')
,bio: DS.attr('string')
,coach: DS.attr('boolean')
,athlete: DS.attr('boolean')
});
App.Person.FIXTURES = [
{
id: 10
,fname: 'Jonny'
,lname: 'Batman'
,sport: 'Couch Luge'
,bio: 'Blah, blah, blah'
,coach: true
,athlete: true
}
,{
id: 11
,fname: 'Jimmy'
,lname: 'Falcon'
,sport: 'Cycling'
,bio: 'Yada, yada, yada'
,coach: false
,athlete: true
}
];
I am trying to set up a route to filter the person model and return only coaches. Just to make sure I can access the data, I have simply used a findAll on the person model.
App.CoachesRoute = Ember.Route.extend({
model: function() {
return this.store.findAll('person');
}
});
Now though, I am trying to implement the filter method detailed on the bottom of the Ember.js Models - FAQ page.
App.CoachesRoute = Ember.Route.extend({
model: function() {
var store = this.store;
return store.filter('coaches', { coach: true }, function(coaches) {
return coaches.get('isCoach');
});
}
});
The coaches route is not working at all with the new route implemented and the old one commented out. I am using the Ember Chrome extension and when using the filter route the console responds with, Error while loading route: Error: No model was found for 'coaches'. Apparently the route is not working, specifically the model. No kidding, right? What am I missing in my filter model route?
Thank you in advance for your help.
The error message is spot on- there is no CoachModel. I think you need to do this:
App.CoachesRoute = Ember.Route.extend({
model: function() {
var store = this.store;
return store.filter('person', { coach: true }, function(coaches) {
return coaches.get('isCoach');
});
}
});

Ember.js access model values

I'd like to be able to modify/validate data before actually saving.
Model
App.Post = DS.Model.extend({
title: DS.attr('string'),
author: DS.attr('string'),
date: DS.attr('date', { defaultValue: new Date() }),
excerpt: DS.attr('string'),
body: DS.attr('string')
});
Route
App.PostsNewRoute = Ember.Route.extend({
model: function() {
return this.get('store').createRecord('post');
},
actions: {
doneEditing: function() {
debugger;
this.modelFor('postsNew').save();
this.transitionTo('posts.index');
}
}
});
So, the questions, before the .save() I want to, let's say, validate that the title is not empty or so.
Everything I've tried gets undefined, or [Object object] has no .val() method. I don't know how to get to the values of the model. How can I do that?
And the other thing I have in mind. Is that defaultValue working as intended? I want to set Date() to every new created post. Somehow date is not being recorded since it's not showing.
Thanks.
App.PostsNewRoute = Ember.Route.extend({
model: function() {
return this.get('store').createRecord('post');
},
actions: {
doneEditing: function() {
debugger;
var model = this.modelFor('postsNew');
var title = model.get('title');
model.save();
this.transitionTo('posts.index');
}
}
});

Ember.js - Binding to another controller's model

In my project, I have the following three models:
Club Model: represents a sports club. It has one clubMeta and many customCourts.
ClubMeta Model: club related information relevant to the app.
CustomCourt Model: belongs to club. A club should have customCourts only if clubMeta.customCourtsEnabled is true.
Club
var Club = DS.Model.extend({
... bunch of properties ...
clubmeta: DS.belongsTo('App.Clubmeta'),
customCourts: DS.hasMany('App.CustomCourt')
});
module.exports = Club;
Clubmeta
var Clubmeta = DS.Model.extend({
... bunch of properties ...
customCourtsEnabled: DS.attr('boolean'),
club: DS.belongsTo('App.Club')
});
module.exports = Clubmeta;
CustomCourt
var CustomCourt = DS.Model.extend({
name: DS.attr('string'),
glass: DS.attr('boolean'),
indoor: DS.attr('boolean'),
single: DS.attr('boolean'),
club: DS.belongsTo('App.Club')
});
module.exports = CustomCourt;
What I need to do is a template where the club (which is the logged in user) can add customCourts only if clubmeta.customCourtsEnabled is true. As I was told in another SO question, I should be using an ArrayController to handle CustomCourts.
Everything is ok until this point, the problem comes because CustomCourtsController needs to know about club and clubmeta. I have tried this, with some variations to the binding path:
var ClubCourtsController = Ember.ArrayController.extend({
needs: ['currentClub'],
customCourtsEnabledBinding: Ember.Binding.oneWay("App.currentClubController.content.clubmeta.customCourtsEnabled"),
...
});
CurrentClubController
var CurrentClubController = Ember.ObjectController.extend({
init: function() {
this._super();
console.log('Retrieving club ' + App.clubId);
this.set('content', App.Club.find(App.clubId));
}
});
module.exports = CurrentClubController;
But ClubCourtsController.customCourtsEnabled always returns undefined. What is the right way to do this?
ClubCourtsController.customCourtsEnabled always returns undefined. What is the right way to do this?
You're on the right track. For starters the right way to do the binding is via the controllers property:
var ClubCourtsController = Ember.ArrayController.extend({
needs: ['currentClub'],
customCourtsEnabledBinding: Ember.Binding.oneWay("controllers.currentClub.clubmeta.customCourtsEnabled"),
});
Beyond that, it's generally best practice to wire things together in your route's setupController hook instead of a controller init. So even if you've got that binding right, could be other issues causing the customCourtsEnabled property to be undefined. I've posted a working example on jsbin here: http://jsbin.com/ubovil/1/edit
App = Ember.Application.create({
clubId: 1
});
App.Router.map(function() {
this.route("customCourts", { path: "/" });
});
App.Club = Ember.Object.extend({});
App.Club.reopenClass({
find: function(id) {
return App.Club.create({
id: id,
clubmeta: App.ClubMeta.create({
customCourtsEnabled: true
})
});
}
});
App.ClubMeta = Ember.Object.extend({});
App.CurrentClubController = Ember.ObjectController.extend({});
App.ApplicationController = Ember.Controller.extend({
needs: ['currentClub']
});
App.ApplicationRoute = Ember.Route.extend({
setupController: function(controller) {
controller.set('controllers.currentClub.content', App.Club.find(App.clubId));
}
});
App.CustomCourtsController = Ember.ArrayController.extend({
needs: ['currentClub'],
customCourtsEnabledBinding: Ember.Binding.oneWay("controllers.currentClub.clubmeta.customCourtsEnabled")
});
App.CustomCourtsRoute = Ember.Route.extend({
setupController: function(controller) {
controller.set('content', ['Court a', 'Court b', 'Court c']);
}
});
You need to access the controller via the controllers property
ClubCourtsController = Ember.ArrayController.extend({
needs: ['currentClub'],
customCourtsEnabledBinding: Ember.Binding.oneWay("controllers.currentClub.clubmeta.customCourtsEnabled"),
...
});