Ember: View is not updating after request, when using RESTAdapter - ember.js

As starting point we used http://todomvc.com/architecture-examples/emberjs/ .
We changed the FixtureAdapter to a RESTAdapter and performed the following changes:
Todos.TodosActiveRoute = Ember.Route.extend({
model: function(){
// ** OLD CODE **
// return this.store.filter('todo', function (todo) {
// return !todo.get('isCompleted');
// });
// ** NEW CODE **
return this.store.findQuery('todo', {isCompleted: false})
},
renderTemplate: function(controller){
this.render('todos/index', {controller: controller});
}
});
We can load the todo items correctly, but if we want to delete one of them a DELETE request is successfully sent to the backend but the todo-item is not removed from the UI.
EDIT:
The delete action is:
removeTodo: function () {
var todo = this.get('model');
todo.deleteRecord();
todo.save();
}

The problem is with using findQuery here. It results in a non live array. That's why the view is not updated after delete (I think if you add a todo, it should neither work)
You can use store.filter passing it the query and the filter function. I think it should work as you expect.
Todos.TodosActiveRoute = Ember.Route.extend({
model: function(){
return this.store.filter('todo', {isCompleted: false}, function (todo) {
return !todo.get('isCompleted');
});
},
renderTemplate: function(controller){
this.render('todos/index', {controller: controller});
}
});

Related

Sorting ember-data live array in route model hooks

in a ember route's model hook the following works fine:
model: function () {
return this.modelFor('foo').get('bar');
}
Backed by ember-data, I can delete some of foo's bars somewhere else and it will be updated automagically (live array).
Now, I want this to be sorted (and user in sub-routes, so I have to do this in the route, not in the controller).
model: function () {
return this.modelFor('foo').get('bar')
.then(function (data) {
return data.sortBy('baz');
});
},
... does the job only the first time around, because I'm losing the updating.
Is there a way to write automatic updating sorting in line? What is the ember way to solve this?
To answer my own question, based on the answer from Gaurav:
model: function () {
return this.modelFor('foo').get('bar')
.then(function (data) {
return Ember.ArrayProxy.extend({
arrangedContent: Ember.computed.sort('content', 'props'),
props: ['baz:asc']
}).create({
content: data});
});
},
You can create an Ember Object for your model that has a computed property that is the sorted data.
model: function () {
return this.modelFor('foo').get('bar')
.then(function (data) {
return Ember.Object.extend({
arrangedData: Ember.computed.sort('model', 'props'),
props: ['baz:asc']
}).create({ model: data });
});
},
The Ember.Object.extend part should probably be extracted somewhere so it can be reused in other routes.

Multiple models to Ember route

I have a list of printers
GradingX.PrintersRoute = Ember.Route.extend({
model: function () {
var printerList = Em.A();
//Ember.
$.getJSON("http://localhost/printers").then(function (data) {
data.forEach(function (item) {
printerList.addObject(item);
}), function () {
alert("$.getJSON failed!");
};
});
return printerList;
},
});
That I'm trying to access from my header
GradingX.HeaderRoute = Ember.Route.extend({
model: function () {
//console.log("test in header model route");
//return Ember.Object.create({
return Ember.RSVP.hash({
printers: What Goes Here?,
otherObjects: More Stuff Here
});
},
});
I'm trying to follow the answer here https://stackoverflow.com/a/20523510/697827, but since I'm not accessing through Ember-Data I don't think this.store.find('printers') is going to get me what I need.
I'm missing something. Please help!
RSVP.hash expects an object with keys and promises as values. So I think that the following could work:
GradingX.HeaderRoute = Ember.Route.extend({
model: function () {
return Ember.RSVP.hash({
printers: $.getJSON("http://localhost/printers"),
otherObjects: $.getJSON("http://localhost/???")
});
},
});
In the referenced answer is used this.store.find, which also returns a promise, but it's resolved with a DS.RecordArray (an array like object provided by ember data). So what matters for RSVP.hash are promises.

How to avoid too many empty records?

Ember : 1.5.0-beta.2
Ember Data : 1.0.0-beta.7
I have the following router:
App.Router.map(function() {
this.resource('posts', function() {
this.route('new');
});
});
My PostsNewRoute creates a new record in the model hook:
App.PostsNewRoute = Ember.Route.extend({
model: function() {
return this.store.createRecord('post');
}
});
Since I don't want transient record to be visible, I filter them out in my PostsRoute:
App.PostsRoute = Ember.Route.extend({
model: function() {
this.store.find('post');
return this.store.filter('post', function(post) {
return !post.get('isNew');
});
}
});
This works as expected, but every transition to posts.new add a new record to the store, which is something I would like to avoid. So, instead of calling createRecord every time the model hook is called, I filter the store for an empty record and return this if there is one found:
App.PostsNewRoute = Ember.Route.extend({
model: function() {
var route = this;
return this.store.filter('post', function(post) {
return post.get('isNew');
}).then(function(result) {
return result.get('firstObject') || route.store.createRecord('post');
);
});
This gives me at the most one empty record.
My question: is there a better way to avoid my store being populated with (many) empty records ?
UPDATE:
Instead of filtering on the isNew attribute, I can probably use currentModel:
model: function() {
this.get('currentModel') || this.store.createRecord('post');
};
You can use this addon https://github.com/dockyard/ember-data-route to clean up when you leave a /new route. It hooks into the willTransition action hook that gets called on the route whenever a transition occurs.
The source code is a short read: https://github.com/dockyard/ember-data-route/blob/master/addon/mixins/data-route.js.
The alternative would be to not create a new record in the model hook, but according to a comment of yours it doesn't seem to be an option.

Ember App Kit and testing model hook

In Ember App Kit, there are a number of testing examples that ship with the initial repo. One of those is a basic Route Unit test. This test is trivial, if the data is hard-coded in the model hook, like this:
test("#model", function(){
deepEqual(route.model(), ['red', 'yellow', 'blue']);
});
How do you use the isolated container to test the model hook if it returns a promise from ember-data?
Here's the test:
import Activities from 'appkit/routes/activities';
var route;
module("Unit - ActivitiesRoute", {
setup: function(){
var container = isolatedContainer([
'route:activities'
]);
route = container.lookup('route:activities');
}
});
test("#model", function(){
deepEqual(route.model(), ['activity', 'activity2', 'activity3']);
});
And the actual Route's model hook:
export default Ember.Route.extend({
model: function() {
return this.get('store').find('activity');
}
});
UPDATE:
After implementing the different approaches below from kingpin2k. Here is a summary of the outcomes.
First approach: works great ... yet no promise.
Second approach: returns the promise object (appears to be resolved), but the array, and correct values are assigned to _detail property.
test("#model", function(){
deepEqual(route.model()['_detail'], ['activity', 'activity2', 'activity3']); //passes
});
I'd like for store creation to be taken care of within the module setup().
...
module("Unit - ActivitiesRoute", {
setup: function(){
var container = isolatedContainer([
'route:activities'
]);
route = container.lookup('route:activities');
var store = {
find: function(type){
return new Em.RSVP.Promise(function(resolve){
resolve(['activity', 'activity2', 'activity3']); // or made up model(s) here
});
}
};
route.set('store', store);
}
});
And the test:
test("#model", function(){
deepEqual(route.model(), ['activity', 'activity2', 'activity3']); // ???
});
Third approach:
...
module('Unit - ActivitiesRoute', {
setup: function() {
var container = isolatedContainer([
'route:activities'
]);
route = container.lookup('route:activities');
var store = {
find: function() {
var promise = new Ember.RSVP.Promise(function(resolve) {
Em.run.later(function() {
resolve(Activity.FIXTURES);
}, 10);
});
return Ember.ArrayProxy.extend(Ember.PromiseProxyMixin).create({
promise: promise
});
}
};
route.set('store', store);
}
});
And in the test, calling route.model() returns an empty object {} :
test("#model", function(){
deepEqual(route.model(), Activity.FIXTURES); // returns {}
});
UPDATE #2
It was also necessary to add asyncTest() instead of test() and to also call start() to prevent the test runner from hanging.
asyncTest('#model', function(){
Em.run(function(){
route.model().then(function(result){
ok(result);
equal(result, Activity.FIXTURES);
start();
});
});
});
Simple approach, it's a unit test, so really you aren't testing the store, so setup a mock store and result.
route = container.lookup('route:activities');
var store = {
find: function(type){
equal(type, 'activity', 'type is activity');
return ['activity', 'activity2', 'activity3'];
}
}
route.set('store', store);
Even better you can also replicate the promise
route = container.lookup('route:activities');
var store = {
find: function(type){
equal(type, 'activity', 'type is activity');
return new Em.RSVP.Promise(function(resolve){
resolve(['activity', 'activity2', 'activity3']); // or made up model(s) here
});
}
}
route.set('store', store);
If you want to more closely replicate Ember Data you might use an ArrayProxy implementing the PromiseProxyMixin...
route = container.lookup('route:activities');
var store = {
find: function(type){
equal(type, 'activity', 'type is activity');
var promise = new Ember.RSVP.Promise(function(resolve){
Em.run.later(function(){
resolve(['activity', 'activity2', 'activity3']);
}, 10);
});
return Ember.ArrayProxy.extend(Ember.PromiseProxyMixin).create({
promise: promise
});
}
}
route.set('store', store);
Update
Using your last approach you should implement it like this
test("#model", function(){
route.model().then(function(result){
deepEqual(result, Activity.FIXTURES); // returns {}
});
});
But, there is something tricky here, since it has an async response you'll want to wrap it in an Ember run loop
test("#model", function(){
Em.run(function(){
route.model().then(function(result){
deepEqual(result, Activity.FIXTURES); // returns {}
});
});
});

Empty controller blocks view. Why?

I have been experimenting with using Ember with a JSON server but without without ember-data. My test app renders a directory of images from a small JSON structure (generated from a little Go server).
Can anyone explain to me why, if I uncomment the App.FileController in the code below, the corresponding File view fails to render?
window.App = Ember.Application.create();
App.Router.map(function() {
this.resource('files',function(){
this.resource('file',{path:':file_id'});
});
});
App.FilesRoute = Ember.Route.extend({
model: function() {
return App.File.findAll();
}
});
App.FileRoute = Ember.Route.extend({
setupController: function(controller, args) {
controller.set('model', App.File.find(args.id));
},
model: function(args) {
return App.File.find(args.file_id);
}
});
App.File = Ember.Object.extend({
urlPath: function(){
return "/pics/" + this.get('id');
}.property('id'),
});
If I uncomment this, things break:
// App.FileController = Ember.Controller.extend({
// });
(namely, the File sub-view no longer renders at all.)
App.File.reopenClass({
find: function(id){
file = App.File.create({'id':id});
return file;
},
findAll: function() {
return $.getJSON("http://localhost:8080/api/").then(
function(response) {
var files = [];
response.Files.forEach(function (filename) {
files.push(App.File.create({'id':filename}));
});
return files;
}
);
},
});
Also, is there something fundamental that I'm doing wrong here?
As noted by Finn MacCool and agmcleod I was trying to use the wrong type of controller. The correct lines should be:
App.FileController = Ember.ObjectController.extend({
});
Not that I need to explicitly set a FileController in this small example. However, should I go on to expand the code I will no doubt need one and will need to use the correct one.