Make controller property persistent - ember.js

What is the best way to remember the property value of a controller? Take a look here:
jsbin example
I want to remember if an element was expanded, but only during the current session, I don't want to save this value into the datastore. The problem is, doing the following steps:
Expand "Artist"
Expand "Album"
Collapse "Artist"
Expand again "Artist"
"Album" is also collapsed! The value isExpanded from the "Album" was lost, seems that ember recreates the controller every time. Which would we a good solution to remember the value of isExpanded?

If you want the value to be persisted past the lifetime of the controller then you need to save it in a controller that will stay in scope as long as you want it to live (I'm not sure what your full intent is, but if it's really a lifetime of the page value you may want to store it on the application controller)
http://jsbin.com/osoFiZi/5/edit
App.AlbumController = Ember.ObjectController.extend({
needs: ['artist'],
actions: {
toggleExpanded: function() {
this.toggleProperty('controllers.artist.isAlbumsExpanded');
}
}
});

You can add property to model
App.Artist = DS.Model.extend({
isExpanded: false, // this property will not be included into PUT request when you will save record
name: DS.attr('string'),
albums: DS.hasMany('album', {async: true})
});
and toggle it in controller
actions: {
toggleExpanded: function() {
this.toggleProperty('model.isExpanded');
}
}
http://jsbin.com/OtEBoNO/2/edit

Related

Clean Ember 1.13+ way of knowing if child route is activated

Assume we have an Article model as follows:
export default DS.Model.extend({
author: DS.belongsTo('user'),
tagline: DS.attr('string'),
body: DS.attr('string'),
});
Assume also that we have a lot of pages, and on every single page we want a ticker that shows the taglines for brand new articles. Since it's on every page, we load all (new) articles at the application root level and have a component display them:
{{taglines-ticker articles=articles}}
{{output}}
That way we can visit any nested page and see the taglines (without adding the component to every page).
The problem is, we do not want to see the ticker tagline for an article while it's being viewed, but the root-level taglines-ticker has no knowledge of what child route is activated so we cannot simply filter by params.article_id. Is there a clean way to pass that information up to the parent route?
Note:
This is not a duplicate of how to determine active child route in Ember 2?, as it does not involve showing active links with {{link-to}}
Ember is adding a proper router service in 2.15; this exposes information about the current route as well as some methods that allow for checking the state of the router. There is a polyfill for it on older versions of Ember, which might work for you depending on what version you're currently using:
Ember Router Service Polyfill
Based on the RFC that introduced that service, there is an isActive method that can be used to check if a particular route is currently active. Without knowing the code for tagline-ticker it's hard to know exactly how this is used. However, I would imaging that you're iterating over the articles passed in, so you could do something like:
export default Ember.Component.extends({
router: Ember.inject.service(),
articles: undefined,
filteredArticles: computed('articles', 'router.currentRoute', function() {
const router = this.get('router');
return this.get('articles').filter(article => {
// Return `false` if this particular article is active (YMMV based on your code)
return !router.isActive('routeForArticle', article);
});
})
});
Then, you can iterate over filteredArticles in your template instead and you'll only have the ones that are not currently displayed.
You can still use the link-to component to accomplish this, and I think it is an easy way to do it. You aren't sharing your taglines-ticker template, but inside it you must have some sort of list for each article. Make a new tagline-ticker component that is extended from the link-to component, and then use it's activeClass and current-when properties to hide the tagline when the route is current. It doesn't need to be a link, or look like a link at all.
tagline-ticker.js:
export default Ember.LinkComponent.extend({
// div or whatever you want
tagName: 'div',
classNames: ['whatever-you-want'],
// use CSS to make whatever class you put here 'display: none;'
activeClass: 'hide-ticker',
// calculate the particular route that should hide this tag in the template
'current-when': Ember.computed(function() {
return `articles/${this.get('article.id')}`;
}),
init() {
this._super(arguments);
// LinkComponents need a params array with at least one element
this.attrs.params = ['articles.article'];
},
});
tagline-ticker being used in taglines-ticker.hbs:
{{#tagline-ticker}}
Article name
{{/tagline-ticker}}
CSS:
.hide-ticker {
display: none;
}
I tried to extend the LinkComponent, but I ran into several issues and have still not been able to get it to work with current-when. Additionally, if several components need to perform the same logic based on child route, they all need to extend from LinkComponent and perform the same boilerplate stuff just to get it to work.
So, building off of #kumkanillam's comment, I implemented this using a service. It worked perfectly fine, other than the gotcha of having to access the service somewhere in the component in order to observe it.
(See this great question/answer.)
services/current-article.js
export default Ember.Service.extend({
setId(articleId) {
this.set('id', articleId);
},
clearId() {
this.set('id', null);
},
});
routes/article.js
export default Ember.Route.extend({
// Prefer caching currently viewed article ID via service
// rather than localStorage
currentArticle: Ember.inject.service('current-article'),
activate() {
this._super(arguments);
this.get('currentArticle').setId(
this.paramsFor('articles.article').article_id);
},
deactivate() {
this._super(arguments);
this.get('currentArticle').clearId();
},
... model stuff
});
components/taglines-ticker.js
export default Ember.Component.extend({
currentArticle: Ember.inject.service('current-article'),
didReceiveAttrs() {
// The most annoying thing about this approach is that it
// requires accessing the service to be able to observe it
this.get('currentArticle');
},
filteredArticles: computed('currentArticle.id', function() {
const current = this.get('currentArticle.id');
return this.get('articles').filter(a => a.get('id') !== current);
}),
});
UPDATE:
The didReceiveAttrs hook can be eliminated if the service is instead passed through from the controller/parent component.
controllers/application.js
export default Ember.Controller.extend({
currentArticle: Ember.inject.service('current-article'),
});
templates/application.hbs
{{taglines-ticker currentArticle=currentArticle}}
... model stuff
});
components/taglines-ticker.js
export default Ember.Component.extend({
filteredArticles: computed('currentArticle.id', function() {
const current = this.get('currentArticle.id');
return this.get('articles').filter(a => a.get('id') !== current);
}),
});

Temporary Non-Persistent Record with Ember-Data 1.0.0-beta

I'm new to Ember and Ember-data and am deciding whether to use Ember-Data or one of the other persistence libraries. In order to evaluate, I'm experimenting with writing a small Rails-backed app.
One of my routes can be considered similar to the Todo MVC app that is frequently used in examples.
In my template, I have a number of input fields that represent attributes within the model. Furthermore, I also have one element in the model that represents a hasMany relationship.
Models:
App.CompanyModel = DS.Model.extend
company: DS.attr()
desc: DS.attr()
contacts: DS.hasMany('company_contact')
App.CompanyContactModel = DS.Model.extend
firstname: DS.attr()
lastname: DS.attr()
...
Within my controller, I want to be able to create a new CompanyModel record (and by virtue, add one or more contacts models to it), but not have it appear within the controller's instance of the CompanyModel until I'm ready to do so.
Currently, when a user wants to add a new record, I have a component that calls an action in my controller as follows:
#set('new_company',
#store.createRecord('company')
)
This actually works fine, except for one thing. My view has to populate the individual attributes within "new_company", which it does, however, the record is immediately added to the controller's model instance and appears in the list of records; I only want the newly created record to be visible in the table once a particular action has taken place.
Instead of instantiating new_company with createRecord, I could do something like this:
#set('new_company',
Ember.Object.create
companyname: ''
desc: ''
contacts: [
firstname: ''
lastname: ''
]
)
And then do a #store.createRecord('company', #get('new_company')), however, given I've already defined my attributes in the model, it doesn't feel very DRY to me.
I'm using Ember 1.5.0 and Ember-Data 1.0.0-beta.7.
It appears I'm not the first person to have this issue (create temporarty non persistent object in Ember-Data), but it appears that Ember-Data has sufficiently changed to make all of these solutions inoperable.
Thanks for your help!
You're real issue is you're using what's considered a live collection. I'm going to assume in your route you've done something like this:
App.FooRoute = Em.Route.extend({
model: function(){
return this.store.find('company');
}
});
find with no parameters says, hey Ember Data, find me all the records that are company. Well Ember Data shoots off a request to your back-end, then returns store.all('company'). all is a live collection that will always have all the records of that type currently in the store. In your case, you are saying I want to avoid any record that is new. There are a couple of ways to handle this.
Create a static list. (You'll need to manually add/remove objects to/from this list).
App.FooRoute = Em.Route.extend({
model: function(){
return this.store.find('company').then(function(companies){
return companies.toArray();
});
}
});
Example: http://emberjs.jsbin.com/OxIDiVU/641/edit
Create a computed property that only shows records that aren't new
App.FooRoute = Em.Route.extend({
model: function(){
return this.store.find('company');
}
});
App.FooController = Em.ArrayController.extend({
savedRecords: function(){
return this.get('model').filterBy('isNew', false);
}.property('model.#each.isNew')
// shorthand this could be written like this
// savedRecords: Ember.computed.filterBy('model', 'isNew', false)
});
Then in your template you would iterate over the computed property
{{#each item in savedRecords}}
{{/each}}
Example: http://emberjs.jsbin.com/OxIDiVU/640/edit

Ember-Data computed property and defaultValue

I have a model in ember-data defined as:
App.Note = DS.Model.extend({
content: attribute('string'),
createdDate: attribute('string', {
defaultValue: function() {return new Date()}
}),
title: function() {
// do stuff
}.property('content', 'createdDate')
});
I notice that when I create a new object with:
this.store.createRecord('note');
The title property is not computed. I assumed that the default value would trigger the property to update, but it's not. How can I get a default value to also trigger a computed property to fire?
I believe the problem is that you are using 'content' as a property name. I would avoid using that word, as Ember tends to use it a lot itself and it can mess things up. Here is a jsbin of your code woriking: http://emberjs.jsbin.com/jebugofo/6/edit?html,css,js,output . Simply needed to get rid of that name for the property.

Ember.js sorting and filtering children of a hasMany relationship in parent route

Update #2
I found that when I refactored the filtering logic to take place in a compound computed property within the PostController instead of within individual routes, I was able to get it working. The solution was ultimately dependent upon a single dynamic variable set by the specific #linkTo route action that triggered filtering changes within a PostController computed property. I have a lot of work to catch up on so I can't post the solution to this specific question now, but when I can I will detail an explanation of the solution below. For now I have marked #twinturbo's answer as correct for the partial but incredibly helpful guidance he gave below. Thanks again man!! Much appreciated!!
Update #1
The latest fiddle is at http://jsfiddle.net/aZNRu/14/ with #twinturbo's help, sorting the "rank" attribute of Comments in its Post parent controller is working, along with basic filtering. Still having the problem of not getting auto updating views when in a filtered route and a new comment is created.
Original Question
I see that there is talk of combining the sortable mixin with filtering functionality, but for now, as you can see in my jsfiddle example, I'm having issues with both sorting and filtering:
1) I can't figure out how to sort by a specific child attribute in the controller of its parent. If we have:
App.Post = DS.Model.extend({
title: DS.attr('string'),
post: DS.attr('string'),
comments: DS.hasMany('App.Comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('App.Post'),
description: DS.attr('string'),
isActive: DS.attr('boolean'),
rank: DS.attr('number')
});
App.Router.map(function() {
this.resource("posts", { path: "/" }, function() {
this.resource('post', { path: ':post_id' }, function() {
this.route('active');
this.route('inactive');
});
});
});
I want to be able to sort each post's comments in ascending order by it's "rank" attribute. I want to do something like:
App.PostController = Ember.ObjectController.extend({
sortProperties: ['comments.rank']
but for one, I think sortProperties only works on arrayControllers, and I don't think it can work more than one level deep. How could I achieve this?
2) The second problem is not getting auto-updating views when in a filtered route. For example, if you view the jsfiddle and go into the active filtered route by clicking "Active Comments" you get a nice filtering effect on the current data. But if you remain in the active route and create a new record that is active by clicking "Add New Comment," the record does not automatically render under "Active," and only appears if you click on another route and then return to it.
Am I setting up the route filtering incorrectly in the route or referencing it wrong in the template?
App.PostActiveRoute = Ember.Route.extend({
setupController: function() {
var post = this.controllerFor('post').get('model'),
comments = post.get('comments');
var activeComments = comments.filter(function(comment) {
if (comment.get('isActive')) { return true; }
});
this.controllerFor('post').set('filteredComments', activeComments);
}
});
<ul>
{{#each comment in filteredComments}}
<li>{{comment.rank}} {{comment.description}} - isActive: {{comment.isActive}}</li>
{{/each}}
</ul>
Any insight you could give on these issues would be greatly appreciated!
but for one, I think sortProperties only works on arrayControllers, and I don't think it can work more than one level deep. How could I achieve this?
You are correct that sortProperties only works on Ember.ArrayController.
You really don't need to do anything fancy to achieve this. Simply wrap the comments array in a new ArrayProxy that includes the sortable mixin. Then you can sort the comments. Then you don't need a nest property because you're sorting an array of comments.
Please don't extend DS.ManyArray. There is no need for that.
As for sorting and filtering, you need to use composition here. That means creating something like filteredContent and sortedContent. Then you can have sortedContent use filteredContent.
Update:
PostController = Ember.ObjectController.extend({
comments: (function() {
return Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {
sortProperties: ['rank'],
content: this.get('content.comments')
});
}).property('content.comments')
This can be done with a computed property macro, too.
PostController = Ember.ObjectController.extend({
commentSortProperties: ['rank:desc', 'createdAt:asc'],
comments: Em.computed.sort('model.comments', 'commentSortProperties')
});
Take a look at the code here.
Perhaps you can make your many-arrays sortable by extending the store and add the sortable mixin in the createManyArray method? (I did not test if it works)
App.store = DS.Store.create({
createManyArray: function (type, clientIds) {
var array = DS.ManyArray.create(Ember.SortableMixin, { type: type, content: clientIds, store: this });
clientIds.forEach(function (clientId) {
var recordArrays = this.recordArraysForClientId(clientId);
recordArrays.add(array);
}, this);
return array;
}
});
then you can bind to the arrangedContent of the array
{#each comment in filteredComments.arrangedContent}}

How to change DS.Model url in ember-data?

I am new(to ember) and trying to build a search centric Ember App w/ Ember-data also. I wanted to change the url on the fly(based on search string) and the data should change automatically(on the fly). How to do it?
This is my not working code:
Emapp.Data = DS.Model.extend({
first_name: DS.attr('string')
}).reopenClass({
url: Emapp.MyURL.get('url')
});
Emapp.MyURL = Em.Object.create({
urlParam: 'John',
url: function()
{
return 'emb/data.php?id=%#'.fmt(this.get('urlParam'));
}.property('urlParam')
});
When I execute. emapp.MyURL.set('urlParam', 'Adams'). I can inspect and see the url changed to 'Adams'. But data is not fetched again.
Edit: emapp -> Emapp (pointed out by rudi-angela)
As you have made the 'url' property a computed property, Ember takes care of updating this value when the urlParam changes. That is all you have instructed Ember to do here (and apparently it is doing it properly).
But I reckon what you want here is any change in the 'urlParam' property to trigger a fetch action. In that case a solution would be to create a separate object that observes the urlParam and will take action when the 'urlParam' value changes. Something along these lines:
emapp.watcher = Ember.Object.create({
valueBinding: "emapp.MyURL.urlParam",
observer: function() {
console.log("urlParam has changed:");
// perform your fetch here
}.observes("value"),
});
Note: I thought there was a requirement for the namespace to be capitalised (rather Emapp instead of emapp).