REST Adapter model reloading - ember.js

I'm having some difficulty reloading my ember RESTful models, and I'm not sure why. Here's [conceptually] what I'm trying to do... http://jsbin.com/EfuBiNo/4/edit
The only difference between that code and my code is that I'm not using the FixtureAdapter, I'm using the RESTAdapter. Unfortunately, reloading my RESTful models is causing the number of records in the DS.RecordArray to double. So you can see the console is logging that (on every reload) there are two records in the RecordArray.
When I run this with my RestAdapter, the count goes 2...4...8...16....etc. So I'm not sure why it's doubling them every time, but if anybody has any insight on why -- or better yet, another way to reload these records -- I'd be very grateful. Thanks.

If you need to refresh a collection of records after you've already loaded them, you could do something like:
App.ThingsRoute = Ember.Route.extend({
model: function () {
return this.store.find('thing');
},
actions: {
refreshThings: function () {
var controller = this.controller;
this.store.find('thing').then(function (things) {
controller.set('content', things);
});
}
}
});
This will simply fetch all the things again and set the record array as the content on your controller whenever the promise resolves. If the items that come back are already catalogued in your store (the ids are already present) then you won't get a ton of duplicate records hanging around; stuff will just get updated. If there are new records that you didn't previously know about, then you'll get those now on your ThingsController.
This is also useful if you are doing some type of querying:
this.store.find('thing', {color: 'red'})

Related

Fetch new data from API in jQuery plugin's callback

I am new to ember, so please treat me like a fool. What I'm trying to do first is to understand the concept.
In my application I heavily rely on few jQuery plugins they fetch new portion of data in their callbacks, that's how these plugins are designed, but I am not sure how can I trigger them to fetch a new portion of data from API passing to API updated query parameters after plugin has been rendered.
I have wrapped the plugin in a component, in component's template I send data to it as (I use emblem.js syntax here)
= plotly-chart chartData=model
In model I have
//app/models/data-points.js
import DS from 'ember-data';
export default DS.Model.extend({
// time: DS.attr(),
ch1: DS.attr(),
ch2: DS.attr(),
ch3: DS.attr(),
temperature: DS.attr(),
});
And then in component itself I fetch data
//app/components/plotly-chart.js
dataPoints: Ember.computed.map('chartData', function(item){
return item.getProperties('ch1', 'ch2', 'ch3', 'temperature');
}),
and make some manipulations with data, which isn't so important for the question itself.
Ah, and I have a route graph/ which later calls that component
//app/routes/graph.js
import Ember from 'ember';
export default Ember.Route.extend({
queryParams: {
start_timestamp: {
refreshModel: true
},
end_timestamp: {
refreshModel: true
}
},
model(params) {
return this.get('store').query('data-point', params);
}
});
So as you see I have tried to fetch new properties via query params, finally it works great if I just update the url in browser, but now can I trigger new call to API and fetch new data and get this new data in a component itself?
Also I'm struggling to understand what role controllers play in all of these. It is mentioned that controllers will be deprecated soon, but still used here https://guides.emberjs.com/v2.10.0/routing/query-params/
My code seems to work without controllers, so this is really confusing.
Also I suspect maybe I should use services for what I'm trying to achieve, but not sure how.
Ember experts, could you please point me into a right direction? The most important thing is how to fetch new portion of data from API with updated query parameters (query parameters to API itself, not nessesarely the ember application, but I suspect in ember-data it is the same thing? or not %) %) %)).
UPDATE 1
Really I should use services for that, shouldn't I? Pass arguments into a service and query a store there. Would that be a correct pattern?
Then query parameters in url are not the same as querying the store and is an independent thing. Am I right?
but how can I trigger new call to API and fetch new data and get this new data in a component itself?
If you change your queryParam values in a controller using an action (combined with your current route setup) it will adjust your route and re-call your API, as the values are bound together to make this particular use case simple :-) You're about 98% of the way there ... :-)
Re controllers going away, they won't for a long time as the replacement hasn't been worked out yet. You could do some of this in a service if you want to, but there is no need as you are almost done.
Thanks, that make sense though. I just worried I'm doing it wrong.
By they way finally I found a way to access store from the controller Access store from component but:
1. I was unable to take out the data from that variable, probably it's me being stupid.
2. I double it's the right way to access store directly in a component and better to use services for that or rely on “Data Down Actions Up” (DDAU) paradigm?
Finally I was able to fetch new portion of a data calling a controller's action from within the controller, but then the next problem raised - the data was updated, but the JS code did not know about that because I feed the jQuery plugin with this data and it did not pick up changes automatically. I think I might be doing it a wrong way there %)
But finally I get it working by adding an Ember's observer to that variable and in observer calling a redraw function (for chart in this particular place).
#acorncom Thanks!

How to access deleted records in ember?

Assume I have a tasks application.
When the user updates a task an update button is enabled and the number of updated records is displayed. I do not manage to implement this when I delete a record.
For updates this is easily done in the controller:
App.TasksController = Ember.ArrayController.extend({
changedAmount: function(){
#filterBy('isDirty', true).get('length');
}.property('content.#each.isDirty');
})
But then when I delete a record using the deleteRecord function I don't manage to get the amount of changed/deleted records. Example:
App.TasksRoute = Ember.Route.extend({
.
.
actions: {
delete: function(task){
task.deleteRecord()
}
}
});
How can I access the deleted records or at least the amount of them?
My environment:
Ember : 1.3.1.1
Ember Data : 1.0.0-beta.6
Handlebars : 1.2.1
jQuery : 1.10.2
Looks like the property you're looking for is isDeleted. So you could modify that controller to be like:
App.TasksController = Ember.ArrayController.extend({
dirtyTasks: Ember.computed.filterBy('content', 'isDirty', true),
deletedTasks: Ember.computed.filterBy('content', 'isDeleted', true),
changedTasks: Ember.computed.union('dirtyTasks', 'deletedTasks')
});
Update:
I see what you mean about the content being autoupdated. I tracked this one down to the recordArrayManager being used by the Ember Store. When you issue either a find or a filter on the store, what is returned is a filtered record array, and one of the filters applied to that array is that none of the records in it can be in an isDeleted state. You can see that in action here.
Off the top of my head, I can't see a solution to this that I'm particularly satisfied with. But, if you absolutely need the content in your array controller to included deletedRecords, then you would need to override the method I linked to above in a custom RecordArrayManager class, and then set that recordArrayManager in the initialize for your application's store, as seen here.
Here's a jsbin demonstrating it
Note that this is a dirty hack and you really shouldn't do it. Frankly, I think a better solution would be to, instead of deleting the record using ember data methods, come up with your own flagged customIsDeleted state and set the model in that state instead of outright deleting it, if you really want it to stay on the screen.

I just can't slice Ember Data store output

I'm JS beginner and recently using ember.js for ui development I came across a problem that I can't solve.
I'm trying to reduce amount of posts to fit them on one page. Simply calling slice method on return value of this.get('store').find() doesn't work. I also tried to trim content of return value of all function, but still without success. Any ideas?
You can use the following:
App.YourController = Ember.ArrayController.extend({
arrangedContent: function() {
return this.get('content').slice(0 , 10);
}.property('content')
});
Where YourController is the controller that belongs to your route. So the content will be the resolved promise from this.store.find('modelName'). The arrangedContent property is the place where you modify the content when you want to perform filtering, ordering etc. Without changing the content directly and preserving all the data.
Give a look in that sample http://jsfiddle.net/marciojunior/pwQ5b/
If you really are calling slice on the return value of this.get('store').find you will run into trouble. The find function returns a promise and you need the result the promise resolves to.
You can solve this in one of two ways:
If you are using the standard Ember pattern for loading in your model, you should have a model function defined in your route. This will actually wait until the result is resolved and in your controller you can call slice on this.get('content')
If you are loading your data within the controller you will need to so something like below:
c = this
this.store.find('myModel').then(function(result) {
c.set('paginatedContent', result.slice(0, 10));
});
Here we are waiting for the promise returned by find to resolve to a result before setting the paginated content based on that result.

Filtered arrays and since() functionality in ember-data

I have a backend resource that contains user activities and in the application I would like to present activities based on a single day's worth of activities. I have an ArrayController called ActivitiesController defined in the router like this:
this.resource('activities', { path: '/activities/:by_date' }, function() {
this.route('new');
});
The REST API provides the following GET method:
GET /activities/[by_date]
So far this looks pretty symmetrical and achievable but I'm running into two problems:
Parameterized array find. Typically a parameterized route would be serviced by a ObjectController but in this case the by_date parameter simply reduces/filters the array of activities but it's still an array that's returned. I'm not sure how to structure this in the model hook in the ActivitiesRoute so that its effectively doing a "findAll" rather than expecting a singular resultset.
Since functionality. As there is a reasonable network cost in bringing back these arrays of activities I would like to minimize this as much as possible and the REST API supports this by allowing for a since parameter to be passed along with the date of the last request. This way the server simply responds with a 304 code if no records have been updated since the last call and if there are new records only the new records are returned. Is there anyway to get this "out of the box" with ember-data? Does this require building a custom Adaptor? If so, are there any open source solutions that are available?
p.s. I was thinking that part of the answer to #2 might be to incorporate Alex Speller's Query Parameters: http://discuss.emberjs.com/t/query-string-support-in-ember-router/1962/48
What does your route's model hook look like? I am thinking something like this should work:
model: function(params) {
return this.store.find('activity', { by_date: params.by_date });
}

Ember Data's API call signature

I'm a newbie to Ember Data and I've just switched from FIXTURE data to the RESTAdapter but I don't know enough about how to connect the model and the API's call signature. Specifically I'd like to be able to call an endpoint GET /activities/[:user_id]/[:by_date]. This would load an array of "Activity" objects but only those for a given date.
Router:
this.resource('activities', { path: '/activities' }, function() {
this.route('by_date', {path: '/:user_id/:by_date'});
});
Route:
App.ActivitiesByDateRoute = Ember.Route.extend({
serialize: function(activity) {
return {
userId: 1,
dateBy: "2013-07-01"
};
}
});
First off I tried to hard code the values for userId and dateBy making the adjustments to the Route above. Sadly that did not work. I think I understand why -- although I don't have a quick way to fix this -- but more disturbing for me was that when I manually put in the parameters into the URL: http://restful.service.com/api/activities/1/2013-07-01. The results are quite surprising to me:
Initially the debugging messages suggest a success:
This however, is not correct as no network requests are actually made
If you reload the browser, it will now go out and get the Activities but to my surprise it also goes out to find the specified user. Hmmm. That's ok, the user 1 is pulled back successfully.
The Activity, however, is just a GET /activities call which fails because this endpoint needs the user and date qualifier to work. Why weren't these included in the request?
I don't think ember data supports "composite keys" (which is essentially what you are trying to do). You'd probably need to build your own Ajax for that specific model and implement it in the model hook for that specific route. You can always fetch the data and sideload it into ember-data if you'd like to have an ember data model.