EmberJS Model find not up-to-date with underlying store - ember.js

For a simple overview screen I have a developed a route that sets up a controller that does an App.Location.find().
App.LocationsIndexRoute = Ember.Route.extend({
setupController: function(controller) {
controller.set('content', App.Location.find());
},
renderTemplate: function() {
this.render('locations.index',{into:'application'});
}
});
I naively assumed that this would simply go to the store and fetch me all the records, giving me an up-to-date view of the records.
Apparently not....
When an external process starts removing records from the database,
the App.Location.find() keeps on returning these deleted records.
(although the REST call doesn't show them anymore)
If an external
process starts adding records to the database, the
App.Location.find() picks them up.
If I delete the records form
within the Ember app itself the model is correctly updated.
How should I deal with this in my Ember app ? I'd like to have an up-to-date view on whatever is in my database. Right now I need to refresh the page (F5) to get an up to date view. Using the linkTo helpers shows me the stale data.
This seems to be yet another trivial thing that I completely missed in EmberJS. Is it somewhere mentioned in the docs why it behaves like that ? I guess there is a valid philosophy behind this behavior.
My overview screens is simply interested in showing the most up-to-date data. If a record is no longer in the DB the model should not return it anymore.
I've added a sample project in Github that is having this issues.

Try unloading all of the data from the store before you call find():
this.store.unloadAll('widget');
this.store.find('widget');
That will fully refresh your store to reflect what's on your server.

Have you tried App.Location.query() instead of App.Location.find()?

Related

can i createRecord() without using save()?

I'm learning ember from the scratch and i stumbled upon something i can't quite understand:
const newNote = this.store.createRecord('note', {
content: 'once upon a time...',
});
newNote.save().then(this._redirectToNewNote.bind(this));
Is the result of createRecord in the database before saving, or is it like a dummy object? can I use createRecord without saving?
Yes. you can use it without saving, do remember it will be removed from store when you refresh page.
From ember guide
createRecord is used for creating new records on the client side. This will return a new record in the created.uncommitted state. In order to persist this record to the backend you will need to call record.save().

EmberJS view reload with data

I have a view in emberjs that shows results that are on the ember data store, I have a search function that updates the results in the store via rest and so on, however the issue I have is that when the store gets updated it doesn't show it on the view, unless I delete all the records and then fill them again, but if I do that, then results that would've had the same id don't show up, as they were deleted I assume and ember ignores them.
is there a way to clear out the data store without deleting them so that they can still show up?
so far these are the 2 methods I tried.
this.store.unloadAll('things');
this.store.all('things').forEach(function(record){
record.deleteRecord();
})
both have the same issue.
Thanks
Ok I figured it out, all I had to do was use unleadRecord(), lack of documentation does make it a bit harder to find, so it will just work like this
this.store.all('things').forEach(function(record){
record.unloadRecord();
})

Reloading a route's model with server json data and need ember-related opinion

I’m building a map with a search function. Basically, I’d like to store objects from the server within my ember app so that whenever I search for something that collection updates itself with the results from the server so the related view updates itself. It’s all on one page.
So far I have an Application Controller, and a Results ArrayController. Data is shown from the Results Controller. Now I’d need that when a search is requested, it gets JSON from the server and updates the results collection.
First question would be:
How would you build that?
I did a v1 with jQuery only and started a new one with Ember but I’m lost as of how structure-wise should I build it.
I built a small jsbin based on what I have here: http://emberjs.jsbin.com/IYuSIXE/1/
Second question:
How would I change a route's model content? Am I going in the wrong direction?
Thanks a lot
You can do both 1 and 2 with query params, check the documentation here https://github.com/alexspeller/website/blob/a96d9afe4506454b155cc64299e86e558ce3c9f1/source/guides/routing/query-params.md
When your route calls the model it will pass the query params, you can do your search against them
model:function( params, queryParams, transition ) { callToYourBackedEndWithQueryParams}
Second question: How would I change a route's model content? Am I
going in the wrong direction?
When the search is requested, in an action you can call this.transitionTo({queryParams: {sort: 'asc'}});, that will fire up again the model hook and you can do the query against your server again.
What I was looking for is a way to change the model on-the-fly.
So basically if I have this:
App.ResultsRoute = Ember.Route.extend({
model: function() {
// empty array that will contain results
return [];
}
});
I can do this to set the content of the model:
this.get('model').setObjects([{}, {}, {}]);
That way I can dynamically play with the models, load them with objects coming from almost anywhere.

Ember Data and Northwind OData

Could Ember-Data b3+ be used for work against a service like this, http://services.odata.org/V2/Northwind/Northwind.svc. If so, could anyone provide an example on how to use it to read OData.
For example a JSBin showing a list of customers where a customer list item can navigate to the orders of a clicked customer
I think this would be a great boon for developers working against different data protocols to wrap their heads around how to wire up an Ember application with Ember-Data.
I've done this with fixtures but just couldn't really wire it up with actual server data.
Edit
Since I wrote this, I have abandoned Ember and fell back to angular for my SPA data apps. The main reason behind this is Ember Set which you should use for Ember to wire up all its binding internals.
Unfortunately, this is not compatible with most libs like Jaydata or Breeze. At least not when you wish to make changes/saves to your entity service.
Jaydata and Breeze both use a propertyChanged property to monitor changes to your entity and Ember will prevent these changes with a You should use Ember Set error.
I could probably have written some sort of adapter to overcome this problem but really I didn't have time and I use a library "Ember" to make my life easier... not to have headaches on basics such as Data Service Queries.
So... I really love Ember, but unfortunately as long as they dont enhance "Ember Data" or drastically change the Ember Set policy, I can't use it!
Basically, if you plan to use a data library (JayData, Breeze) to update a backend...
DON'T USE EMBER!
Original
I had a look (very quickly!) at ember-data and wasnt thrilled really! It looks promising for Standard REST service which IMHO is not WCF's case.
I ended up using JayData for that purpose and I must say it integrates very well with Ember.
here is a quick snippet to get you going:
//Instanciate the Ember APP
App = Ember.Application.create();
//Tell the APP to initialize but to wait before launching
App.deferReadiness();
//Setup your JayData Store
//Entities.EntityModel was generated by JaySvcUtil
App.myStore = new Entities.EntityModel({
name: 'oData',
oDataServiceHost: <YOUR_WCF_ENDPOINT_URL>
});
//Create your route and populate model data
App.IndexRoute = Ember.Route.extend({
model: function () {
//This passes the toArray() promise to the model
return App.myStore.People.orderBy('it.Name').toArray();
}
});
//When JayData Store is ready, Fire the App
App.myStore.onReady(function () {
App.advanceReadiness();
});
Ember Route Model actually handles the promise given by JayData which allows us to just pass the query. see: http://emberjs.com/guides/routing/asynchronous-routing/#toc_the-router-pauses-for-promises

Where to save detailed user session information for EmberJS app?

I am building my first EmberJS app, and am still trying to wrap my head around the best practices & conventions. I'm using ember-data to talk to a RESTful API, and have ember-auth working well enough to log in and save a user's ID & OAuth2 access token. However, I'd now like to maintain additional user information (e.g. name, email, etc) for use in the navbar and in various other areas of the app.
To do this, I am thinking it would be helpful to have a User object (model) that is read from a separate endpoint (e.g. /users/<id>). Since this info would be needed throughout the app, I'm inclined to store it on the ApplicationController, somewhat like this example from Ember's docs:
App.ApplicationController = Ember.Controller.extend({
// the initial value of the `search` property
search: '',
query: function() {
// the current value of the text field
var query = this.get('search');
this.transitionToRoute('search', { query: query });
}
});
However, my user object wouldn't quite be an action like query or a property like search, so I'm not sure this example applies.
I think I'll eventually want to call something like:
this.get('store').find('user', App.Auth.get('userId'));
but I'm just not sure where in the app that would go.
Main question: is the ApplicationController the right place for this information per Ember conventions, and if so, what might the code look like to retrieve it from the REST API?
Appreciate any thoughts to put me on the right track.
The general approach that I've taken before is to store the currently logged in user as App.CurrentUser. Then you can use it in any template. Once I've pulled the User object I call Ember.set('App.CurrentUser',user) to store it, and then Ember.get('App.CurrentUser') to retrieve it in other routes or controllers.
Here's a short jsbin with the general idea : http://jsbin.com/ucanam/994/edit