I need to delete a model when I leaving a route. I am using the following in the route:
actions : {
willTransition: function(transition){
//Cleanup search model
var model = this.modelFor('route1.index');
model.deleteRecord();
//At this point the model.get('isDeleted') = true
}
}
From ember inspector when I have transitioned to my new route route1.route2, I can still see the model and its isDeleted property is now false.
Why is this not working?
First of all, you willTransition will be also called before you're entering the route, so you have to make sure that the transition's target is different from the current route:
if (transition.intent.name !== this.routeName)
Then, you can probably use something like:
var model = this.modelFor(this.routeName);
instead of manually type the route name.
How did you check that the model is not deleted? Maybe you created a new one?
You need to call the save() method after calling deleteRecord()
actions : {
willTransition: function(transition){
//Cleanup search model
var model = this.modelFor('route1.index');
model.deleteRecord();
model.save();
}
}
Or just use model.destroyRecord(); as it does both
Related
Ember 2.5
I have a page that displays a list of all types of commutes (/commutetypes). To create a new commute type, I go to commutetypes/new.
Once I save the new commute type and transition back to /commutetypes. The new commute type does not display on the list. Can I refresh the model to display it?
// save action in route.
save: function() {
var _this = this;
var com = this.store.createRecord('commutetype', {
name: document.getElementById('nameInput').value,
description: document.getElementById('descriptionInput').value
});
com.save().then(function(){
_this.transitionTo('commutetypes');
});
}
Added model for commutetypes route.
model: function(params) {
return Ember.RSVP.hash({
commutetypes: this.store.query('commutetype', params)
});
},
Can you try to pass in your model inside transitionTo. Also make sure that you endpoint returns a 201 with model instance
com.save().then(function(data){
_this.transitionTo('commutetypes', data);
}
I would also need to make sure that from server side you get instance of model back to ember.
Can you post your route code commute types...maybe you are not loading data there properly
hope it helps
Is it possible to access route model inside route action?
I am passing multiple objects inside a route model to template,
model: function() {
return {
employeeList : this.store.findAll("employee"),
employee : Ember.Object.create()
}
}
From the route action I am want to modify the route model.employee. I tried the following, but I am not getting the object.
actions:{
editAction : function(id) {
var emp = this.get("model");
console.log(emp.employee);
}
}
Can anyone give a solution to get and modify model object(employee)?
First problem is that you should return a promise from the model hook. That way, the transition will wait for the promise to Resolve. return { /*...*/}; returns an object and not a promise, even if the object itself contains promises.
The solution is to use Ember.RSVP.hash like:
model() {
return Ember.RSVP.hash({
employeeList: this.store.findAll('employee'),
employee: Ember.Object.create()
});
}
This will return a promise that resolves when all inner promises resolve.
The second problem is that you can't use this.get('model') in a route. If you think about it the model property is the hook itself and not the resolved model. Solutions:
That action is sent from the controller/template. Can't you pass the model as a parameter? That way you could access the model through the function arguments.
If you absolutely need to, this.modelFor(this.routeName); returns the model for the current route.
You can access the model in route through the controller like this.controller.get('model').
You could also implement the setupController hook and access there the model. You can then do things like this.set('employeeModel', model); for later access.
this.get('context')
gives you access to the model in the route action.
For reasons beyond the scope of this question, I have to populate an Ember data model named Activity in my SearchRoute using Ember.$.getJSON in the model hook like this:
App.SearchRoute = Ember.Route.extend({
model: function (params) {
// Create a promise to return to the model hook. The promise will return a DS.RecordArray.
var modelPromise = new Ember.RSVP.Promise(function (resolve, reject) {
// Make the AJAX call to retrieve activities that match the search criteria
Ember.$.getJSON('/services/activities?query=' + params.q).then(function (data) {
data.activities.forEach(function (activity) {
// If the current activity does not already exist in the store...
if (!this.store.hasRecordForId('activity', activity.id)) {
// add the activity to the store
this.store.createRecord('activity', {
id: activity.id,
title: activity.propertyBag.title
});
}
}.bind(this));
resolve(this.store.all('activity', { query: params.q }));
}.bind(this));
}.bind(this));
// Return the DS.RecordArray as the model for the search route
return modelPromise;
}
});
Then, in my SearchController I do some model sorting and filtering before returning the results from a computed property that is bound to a template that displays the results, like this:
App.SearchController = Ember.ArrayController.extend({
filteredActivities: function () {
var model = this.get('model');
// complete various model sorting and filtering operations
return model;
}.property('model')
});
Here's the template:
<script type="text/x-handlebars" data-template-name="activities">
{{#each item in filteredActivities}}
{{item.title}}
{{/each}}
</script>
Every time a search is executed, the model hook in the SearchRoute is refreshed, the AJAX request is made, and the store is updated with new Activity records, if necessary.
The problem is, even if I do create new records in the store using createRecord and return the new store query results to my model hook, the filteredActivities property does not get fired and the template does not update.
I would think that because I'm returning a newly updated DS.RecordArray to the model hook, that Ember would consider my model as having changed and fire any computed properties watching for changes to the model, but I must be missing something.
Does anybody have any ideas?
Sorry for the long post, and thank you so much for taking the time to consider my issue!
Don't use createRecord. Use push.
http://guides.emberjs.com/v1.10.0/models/pushing-records-into-the-store/
Do you try model.[] or model.#each.propertyNameToObserve in computed property filteredActivities?
Examples with #each: http://guides.emberjs.com/v1.10.0/object-model/computed-properties-and-aggregate-data/,
http://guides.emberjs.com/v1.10.0/controllers/representing-multiple-models-with-arraycontroller/
I am trying to add model to a hasmany relationship. In my route I have:
App.CourseRoute = Ember.Route.extend({
model: function(){
return this.store.find('course','-JNPcfHFQC8FNwyt_-Wh');
}
});
and in my controller I have a save action:
App.CourseController=Ember.ObjectController.extend({
actions: {
save: function() {
var _this = this;
var course = this.get('model');
_this.get('session').get('user').get("courses").pushObject(course)
_this.get('session').get('user').save()
}
}
});
The session property refers a global sessions object that is injected into the controller. This project is using firebase and emberFire data adapter. No errors are being thrown and no data is updated on the firebase backend. I can't seem to figure out what is going on.
Breakpoint your code before the save call and you'll probably see that this.get('session').get('user') has an isDirty property of false. So the save becomes a no-op. You can try to solve that by callingthis.get('session').get('user').notifyPropertyChange('courses').
I want to make transition after a create a post.
post/new > click submit > rails backend successfully create post and response a json > redirect to newly created post's path
in ember_data_example github source code. they use this approach
transitionAfterSave: function() {
// when creating new records, it's necessary to wait for the record to be assigned
// an id before we can transition to its route (which depends on its id)
if (this.get('content.id')) {
this.transitionToRoute('contact', this.get('content'));
}
}.observes('content.id'),
It works fine, because The model has ID of null when model created, and its ID would change when model saving is successful because this function observes change of models ID.
But maybe, this function will be executed whenever model's ID property is changed.
I'm finding some more semantic way.
I want transition to be executed
when the model's status is changed to 'isDirty' = false && 'isNew' == true form 'isDirty' = true, 'isNew' = false.
How can I implement this?
Ideally, the id is not supposed to change. However, you are correct, semantically, this method doesn't seem right.
There is a cleaner way to do this:
save: function(contact) {
contact.one('didCreate', this, function(){
this.transitionToRoute('contact', contact);
});
this.get('store').commit();
}
UPDATE 2013-11-27 (ED 1.0 beta):
save: function(contact) {
var self = this;
contact.save().then(function() {
self.transitionToRoute('contact', contact);
});
}
Note for Ember 2.4 It is encoraged to handle saving actions in the component or route level (and avoid controllers). Here's an example below. Note the id on the model object in the transition. And note how we use transitionTo and not transitionToRoute in the route.
actions: {
save() {
var new_contact = this.modelFor('contact.new');
new_contact.save().then((contact) => {
this.transitionTo('contact.show', contact.id);
});
},
actions: {
buttonClick: function () {
Ember.debug('Saving Hipster');
this.get('model').save()
.then(function (result) {
this.transitionToRoute('hipster.view', result);
}.bind(this));
}
}