How to trigger didReceiveAttrs in Ember component - ember.js

Using version 2.17. I have an Ember component inside an /edit route with a controller:
// edit.hbs
{{ingredient-table recipe=model ingredients=model.ingredients}}
Inside my component, I am using a didRecieveAttrs hook to loop through ingredients on render, create proxy objects based off of each, and then build an ingredient table using those proxy objects.
// ingredient-table.js
didReceiveAttrs() {
let uniqueIngredients = {};
this.get('ingredients').forEach((ingredient) => {
// do some stuff
})
this.set('recipeIngredients', Object.values(uniqueIngredients));
}
I also have a delete action, which I invoke when a user wishes to delete a row in the ingredient table. My delete action looks like this:
// ingredient-table.js
deleteIngredient(ingredient) {
ingredient.deleteRecord();
ingredient.save().then(() => {
// yay! deleted!
})
}
Everything mentioned above is working fine. The problem is that the deleted ingredient row remains in the table until the page refreshes. It should disappear immediately after the user deletes it, without page refresh. I need to trigger the didReceiveAttrs hook again. If I manually call that hook, all my problems are solved. But I don't think I should be manually calling it.
Based on the docs, it is my understanding that this hook will fire again on page load, and on re-renders (not initiated internally). I'm having some trouble figuring out what this means, I guess. Here's what I've tried:
1) calling ingredients.reload() in the promise handler of my save in ingredient-table.js (I also tried recipe.reload() here).
2) creating a controller function that calls model.ingredients.reload(), and passing that through to my component, then calling it in the promise handler. (I also tried model.reload() here).
Neither worked. Am I even using the right hook?

I suppose recipeIngredients is the items listed in the table. If that is the case; please remove the code within didReceiveAttrs hook and make recipeIngredients a computed property within the component. Let the code talk:
// ingredient-table.js
recipeIngredients: Ember.computed('ingredients.[]', function() {
let uniqueIngredients = {};
this.get('ingredients').forEach((ingredient) => {
// do some stuff
})
return Object.values(uniqueIngredients)
})
My guess is didReceiveAttrs hook is not triggered again; because the array ingredients passed to the component is not changed; so attrs are not changed. By the way; do your best to rely on Ember's computed properties whenever possible; they are in the hearth of Ember design.

Related

How to update an ember-infinity infinityModel?

I am trying to implement searching with ember-infinity. But, I do not understand the interaction between the route model and infinityModel.
I have the following code:
model() {
...
return this.infinityModel("myModel", {...}, {...})
}
My search action looks like the following:
search(searchCriteria){
const controller = this.get('controller');
...
_this.infinityModel("myModel", {search:searchCriteria, ...}, {...}).then((myMod)=>{
...
controller.set('model', myModel);
});
}
So this works, but the my query gets fired twice when search is called.
The following only fires the query once.
search(searchCriteria){
const _this = this;
...
_this.infinityModel("myModel", {search:searchCriteria, ...}, {...});
}
But my model does not update. However infinityModelUpdated() function is fired. So I assume that means the infiniteModel was updated, which I assume is my model.
I am pretty sure I am missing something simple. But any help would be greatly appreciated.
Just calling the following:
_this.infinityModel("myModel", {search:searchCriteria, ...}, {...});
does not solve your problem; that is because that method call just returns fresh set of new objects retrieved; which is irrelevant with your original model that you had already returned from model hook. In other words; that method call makes the remote call but does not push the objects retrieved to the model that is already returned from the hook method. If you instead set the model of the controller; then of course the new data is updated to the screen; but I am not sure why a second remote call is being made. That might be related with existence of an infinity-loader already existing in your screen.
What I would suggest is to use updateInfinityModel provided instead of setting the model of the controller. Please take a look at the twiddle I have provided. It uses ember-cli-mirage to mock data returned by the server. Anyway, our point is looking at the makeInfinityRemoteCall action.
this.infinityModel("dummy", { perPage: 12, startingPage: 5}).then((myModel)=>this.updateInfinityModel(myModel));
Here a remote call is made upon button click and data is appended to the model already constructed in model hook. I hope this helps you clear things. Please do not hesitate to alter the twiddle yourself or ask further questions you have.
After your comment, I have updated the twiddle to change the model directly. The duplicate remote call that you have mentioned does not seem to be appearing. Are you sure an exact duplicate remote call is being made? Can it be just the case you are using infinity-loader at your template and a remote call for the next page is being made due to appearance within the view port?

Best way to rollback all changes to an Ember Data model

I am using ember-data to edit a user with automatic model resolution
this.route('user', function() {
this.route('edit', { path: ':user_id'})
});
This works fine and the user can modify all aspects of the model DS.attribute, DS.belongsTo and DS.hasMany.
The user can navigate away in a number of ways, in which case all changes should be removed from the model.
Clicking a Cancel button
Clicking the Broswer Back button
Clicking the Save button, the remote request fails, then navigating away from the page.
Just Clicking some other link on the page which takes them somewhere else.
The changes should only be applied if the user explicitly wants them to by clicking the Save button and the server request is successful.
I considered using ember-buffered-proxy but I am not sure how this will cope with DS.belongsTo and DS.hasMany relationships. Regardless, before saving the model I will need to do buffer.applyBufferedChanges(); before saving and if the server fails I am in the save situation as before.
The willTransition hook in the route seems like the obvious place to do this but how can I ensure all changes are removed from the model given rollbackAttributes() only works for DS.attribute controls.
Try utilizing the Ember.Route refresh() method inside the route's willTransition() action hook, like this:
action: {
willTransition() {
const unsavedModel = this.get('unsaved');
if (unsavedModel) {
this.refresh();
}
}
}
The refresh() method can be used for "re-querying the server for the latest information using the same parameters as when the route was first entered."
I've suggested a flag named unsaved, which can default to true, unless it has been set to false at some point during a successful save, prior to transitioning.

Ember.js route hook to be called on every transition

Is there a route hook in Ember.js that is called on every transition, even if the new route is the same as the old route (for example, clicking a top-level navigation link to the same route).
I tried activate, but it's only being called once, and is not being called again when I use the top-level navigation to go to the same route I'm already in.
Example jsFiddle: When I click "Test" the first time, the activate hook is called, but when I click it a second time, it does not.
You can setup a didTransition in the router, exactly how Ember does it for Google Analytics.
App.Router.reopen({
doSomething: function() {
// do something here
return;
}.on('didTransition')
});
See example here: http://emberjs.com/guides/cookbook/helpers_and_components/adding_google_analytics_tracking/
UPDATE: (new link since old is broken)
https://guides.emberjs.com/v1.10.0/cookbook/helpers_and_components/adding_google_analytics_tracking/
Activate is not being called a second time because This hook is executed when the router enters the route... And when you click on that link-to a second time, the router isn't doing anything... As in, no transition is being made (although it is "attempted").
http://emberjs.com/api/classes/Ember.Route.html#method_activate
The method that I have found to work best is observing the currentPath from within a controller. I use this for animations between routes.
In your application controller you can do something like the following:
currentPathChange: function () {
switch(this.get('currentPath')){
case 'test.index':
this.doSomething();
break;
case 'test.new':
this.doSomethingElse();
break;
}
}.observes('currentPath')
You should be able to access almost any part of your app from the application controller, so it's a nice "root hook," I suppose.
Example: http://jsfiddle.net/mattblancarte/jxWjh/2/
Did you already consider the hook willTransition?
http://emberjs.com/guides/routing/preventing-and-retrying-transitions/
App.SomeRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
// do your stuff
}
}
});
Alter/Hack EmberJS code and add a jQuery event trigger inside the doTransition() Function. This is Best but kind of defeating the point.
As of today, 1 year later and Ember 2.0 kind of out, there is NO OTHER WAY :(
Ember does not provide a way to track route-change attempts! This includes URLattemts(history), link-to attempts, hash change attempts etc..

Different Ember Routes or Displaying Two Complex Views in their own context

I have an app with different related concerns. I have a list of items on the left that affect some of the items on the right (think Github Issues), but here's a mockup
All fine, I click Item One and something happens on the right. However, the list on the left has its own routing requirements, it's a resource of items with nested routes. For example when we click on Create New Item we display a new form inline (see bottom left corner)
When I do that it, even if it's on a different outlet, it overrides what is currently rendered in other outlets. In this case the products on the right.
It would be ideal if we could just have different routers for different sections. I know I could just call render and create a new view/controller, but that would require me to handle my own states (am I creating a new item, editing it, looking at the index, etc).
I'm currently looking into query-params as an option.
Any ideas?
I tried many ways to solve this and ended up having a route that encompasses all the various routes that need to coexist render the rest of the parent routes with {{render}}, and making those routes' renderTemplate hook a NOOP (you have to do this specifically, or you will get assertion errors that you are using the singleton form of render twice).
However you don't have to manage your own state -- you can still use nested routes, and their model hooks, and since you are using the singleton form of {{render}} things will still automagically render into their correct spots. To say that another way: if you are using the singleton form of {{render}}, routes can set that controllers model, via the model hook if the route has the same name as the controller, or in either the model or setupController hook of another route using controllerFor.
You can also render into named outlets in the renderTemplate hooks, but I eventually abandoned that approach because I still had problems with disconnectOutlet getting called on things I didn't want disconnected.
Discussion on some outstanding issues indicate that there may eventually be a way to control whether/when routes get torn down and their outlets disconnected, but only when a way to do it has been worked out that won't increase the chance of memory leaks for people doing things the ordinary way.
It's possible to register a different router and inject this into controllers. From ember's source code:
/**
#private
This creates a container with the default Ember naming conventions.
It also configures the container:
....
* all controllers receive the router as their `target` and `controllers`
properties
*/
buildContainer: function(namespace) {
var container = new Ember.Container();
// some code removed for brevity...
container.register('controller:basic', Ember.Controller, { instantiate: false });
container.register('controller:object', Ember.ObjectController, { instantiate: false });
container.register('controller:array', Ember.ArrayController, { instantiate: false });
container.register('route:basic', Ember.Route, { instantiate: false });
container.register('router:main', Ember.Router);
container.injection('controller', 'target', 'router:main');
container.injection('controller', 'namespace', 'application:main');
container.injection('route', 'router', 'router:main');
return container;
}
A second router could be created, registered with the container and injected into certain controllers:
App.Router = Ember.Router.extend();
App.Router.map function () {...}
Then to register
container.register('router:secondary', App.Router);
container.injection('controller:list', 'target', 'router.secondary');

Detect model/URL change for Ember Route

My EmberJS application has a ProjectRoute (/project/:project_id) and a corresponding ProjectController. When viewing a particular project, users can edit its properties, and I'd like the project to automatically be saved when the user stops looking at it.
Currently, what I'm doing is something like this:
Application.ProjectRoute = Ember.Route.extend({
...
exit: function() {
this.get('controller').saveProject();
}
...
});
This works when the user simply closest the project view. However, if the user simply switches to viewing a different project (e.g. goes directly from /project/1 to /project/2), the same route is used (it just uses a different model), and exit is not called.
What I need is a way to detect this transition and call the saveProject function before it happens. Any ideas?
I "solved" it by adding the following to my controller:
Application.ProjectController = Ember.ObjectController.extend({
...
saveOnChange: function() {
var previousProject = this.get('target.projectToSave');
if (previousProject && previousProject.get('isDirty')) {
Application.store.commit();
}
this.set('target.projectToSave', this.get('content'));
}.observes('content')
...
});
This seems to work well. Note that I'm storing the projectToSave property in the route (target) as opposed to the controller, because the controller gets wiped every time the model changes. It feels a little weird/hacky to store this in the route, but the only alternative I could think of was to store it in ApplicationController, which seemed overly broad.