use results from ember data findQuery as ArrayController contentBinding - ember.js

I'm trying to write my first "real" ember app. I've gone through a couple tutorials and I'm now attempting to use ember in conjunction with Ember Data to fetch data from a Rails app and display it.
I've gotten it to fetch the data, parse it, and display it, although I'm not convinced it's in the best way possible. I have an App.itemsController that is similar to this:
App.itemsController = Em.ArrayController.create({
content: App.store.findQuery(App.Item, {visible: true}),
});
I also have an App.ItemIndexView, whose template looks like
{{#each App.itemsController}}
{{id}}{{view App.ItemView item=this}}
{{/each}}
I have a couple of questions about this.
First and foremost, I want to allow a user to change an items visibility to false. I have this code in the App.ItemView file:
acknowledge: function() {
this.item.set('visible', false);
App.store.commit();
}
the record gets updated, however I want that entire item to drop from the view and it doesn't. How do I make this record be removed from App.itemsController.content?
My second question, which may in fact also answer the first, am I completely off in the boondocks as far as my implementation of this? I feel like there should be a way for me to set something like contentBinding: 'App.store.findQuery(App.Item, {visible: true})' and have non-visible ones be removed but I've tried that and nothing shows up. So I'm wondering if something in the way I have my whole app setup is flawed and keeping things from playing nice.

You can use the filter function instead of findQuery:
content: App.store.filter(App.Item, function (item) {
return item.get('visible');
})
The result will be re-evaluated when underlying data change. You still have to get data from the server via find/findAll/findQuery though.

Related

filtering hasMany association in Ember

I'm brand new to Ember and stuck on something that seems very basic. So far in my e-commerce application, I have two models, Product, and Style; a Product has many Styles. For each product, I want to list a subset of the styles (e.g., those that are in stock or out of stock). Coming from a Rails background, I thought I would create a model method in Product called stockedStyles, which filters its styles and returns only those with stocked=true. That didn't work, so I tried another approach of using a controller method, but struck out there too.
Here's the code so far: http://jsbin.com/mufumowabi/1/edit?html,js,console,output
While I would definitely like to know the best practices way of doing this, I'm also curious about other approaches people can suggest that would work but are not recommended -- and why they aren't recommended. Especially when I'm learning something new, I like knowing all the different ways you could do something and then choosing the best/cleanest one.
If there's a tutorial that covers this sort of thing, please send it my way. I couldn't find anything that does this sort of thing, even though it seems so basic.
Lastly, I've found debugging Ember to be somewhat of a black box. For example, for the non-working code posted here, the JS console just says "error". Tips on how I would get more information about why what I'm doing is wrong would be most appreciated as well.
TIA,
fana
I feel your pain. I too came from a rails background expecting similarities in the implementation only to get confused initially. Nobody is ever exaggerating when they claim Ember requires a very large learning investment, but trust me if you stick around it's totally worth it.
Real quick let's take care of a simple goof: You can assign an object property to be either Ember.computed, or function() { /***/ }.property('sdf'); You can't have both. So make that computed function either:
unstockedStyles: Ember.computed.filterBy('styles', 'stocked', false);
or
unstockedStyles: function() {
return this.get('styles').filterBy('stocked', false);
}.property('styles.#each.stocked')
but you can't do both at once.
Ember Models vs Rails Models
Next, the difference with Ember, coming from rails perspective, is that models in Ember.js are intended to be extremely light, serving only as a minimal binding between the data source and the framework overall. Rails takes quite literally the opposite approach, encouraging a very heavy model object (and this is still a large source of contention in the rails community).
In ember.js, the model method helpers are intended to be placed in the controller objects (again, counterintuitive coming from rails). Moving that out, you'll want your models to look like this:
App.Product = DS.Model.extend({
title: DS.attr(),
styles: DS.hasMany('style', { async: true })
});
App.Style = DS.Model.extend({
desc: DS.attr(),
stocked: DS.attr("boolean")
});
The reason for this difference from Rails is that the role of controllers in Ember.js is for "decoration" of your object, whereas in Rails its to handle incoming/outgoing data logic. For each page, you may want to render the same data in different ways. Thus, the model will remain the same, and the controller takes on the burden of encapsulating the extra fluff/computation. You can think of decoration in the same way you were taught the inheritance pattern in OO, with a slight twist:
Let's say you want to have a Person base class (your Ember model), but then you extend it to Teacher and Student subclasses (your controllers) in order to add an additional propertiy that may be from the same type but is not modeled in the same way. For example, Teachers and Students have a many-to-many relationship to courses, but you want to model Students as attending their courses, where Teachers are instructing them. The controller acts as a way to provide such a filter.
ArrayController vs ObjectController
As for the controllers, computed properties for individual records should be placed in the ArrayController's associated ObjectController (we'll call it ProductController), so your controllers now look like this:
App.IndexController = Ember.ArrayController.extend();
App.ProductController = Ember.ObjectController.extend({
unstockedStyles: Ember.computed.filterBy('styles', 'stocked', true)
});
Finally, while Ember.js can automatically associate ObjectControllers with their associated ArrayController for resources defined in your router, you're loading a Product array on the IndexController, so you need to tell IndexController to use ProductController for its item behavior:
App.IndexController = Ember.ArrayController.extend({
itemController: 'product'
});
App.ProductController = Ember.ObjectController.extend({
unstockedStyles: Ember.computed.filterBy('styles', 'stocked', true)
});
Handlebars Binding
Not much here except for a small mistake: while you've enabled a computed property correctly in the proper controller, your {{#each}} loop is instead bound to the original styles array. Change it to use the new property:
{{#each unstockedStyles}}
<li>
{{desc}}, in stock: {{stocked}}
</li>
{{/each}}
And now you're good to go!
JSBin of fixes here: http://jsbin.com/sawujorogi/2/edit?html,js,output

Issues using computed.filter and computed.sort together

Cross-posted at EmberJS forums
In my app I need to filter a list by one or more properties then sort the filtered results by one or more properties. I've accomplished this with
sortProperties: ['manufacturer:asc', 'modelName:asc', 'series:asc'],
filteredContent: Ember.computed.filter('model', function (model) {
return model.get('isActive');
}).property('model.#each.isActive'),
sortedContent: Ember.computed.sort('filteredContent', 'sortProperties').property('filteredContent')
The template binds to sortedContent via a normal {{#each item in sortedContent}}
My issues come when trying to edit an item in that list. Editing the first two items in the list is fine - changing the fields shows the changes in the list with no issues. The problem comes when editing anything lower than the first two items. Any changes get reflected on the proper item as well as other items in the list.
I've created a jsbin that shows the issue. I'm not sure if I'm just missing something on how I'm filtering/sorting/binding or if this is a bug within Ember.
I fixed it, probably the way you were using the filters/sort that was wrong.
Your fixed and simplified controller :
App.ApplicationController = Ember.ArrayController.extend({
sortProperties: ['manufacturer', 'modelName', 'series'],
filteredContent: function() {
return this.get('arrangedContent').filterBy('isActive');
}.property('#each.isActive')
});
I also mapped the template to loop over filteredContent instead of sortedContent
And finally two objects had the same ID (not causing the problem but still...)
The working jsbin

Recommended way to rerender page in Ember after language switch

I need to rerender whole page application after language has switched. I don't like to use observers for it because of performance issues.
Language switch is done by a Ember.View. I tried to rerender parentView after changing Ember.I18n.translations but running into a known bug. It works one time but Ember Inspector shows parentView has dutzend of children views of it's own afterwards. After another switch parentView got destroyed. Just like demonstrated in this JSFiddle.
Here is simplified code of my view:
export default Ember.View.extend({
templateName: 'language-switch',
languageChanged: function() {
// change language
var language = this.get('controller.language.selected');
Ember.I18n.translations = translations[language];
// rerender page
this.get('parentView').rerender();
}.observes('controller.language.selected')
});
There is also a discussion about that problem on discuss.emberjs.com. I tried the suggestions there but they don't work. Last post suggest a work-a-round to map over all views, rerender them and afterwards use a transition. I don't like that one since I am afraid getting side problems by that hack.
I am pretty sure there must be a way to do a language switch in Ember with ember-i18n but what's the right way to do that?
Update:
I tried to implement the hack from discuss.emberjs.com. It's working but it's very limited. I implement it like this in the view:
var self = this;
var currentRoute = self.get('controller.currentRouteName');
this.get('controller.target').transitionTo('loading').then(function(){
self.get('controller.target').transitionTo(currentRoute);
});
Problem is that all data stored in model is lost. I did not find a way to get the current model and use it in transition. Also query parameters are lost. That limitation makes this work-a-round unacceptable for my application.
Update App.reset():
As suggested in comment I tried to use App.reset(). It works better than transitionTo work-a-round but doesn't match all needs. If calling App.reset() queryParams aren't lost but model is reseted. I'm looking for a way to rerender application while keeping current model and queryParams.
It seems that mostly these problem is handled by a full page reload on locale change. E.q. one of the main developers of ember-i18n said so in this discussion.

EmberJS: How do I move stuff out of the application controller?

I have found that nice example of how to display notifications within ember [1]. After noticing it does not work so well with the current ember versions, I created a jsbin and fixed what seemed to be broken: http://emberjs.jsbin.com/decojele/1/edit
I was thinking about putting something like that into its own module, so it can be easily added to existing ember applications. However, the first thing that does not seem to be very suitable for something like this is that it relies on methods and fields (like the notifications array) that are kept within the application controller:
App.ApplicationController = Ember.Controller.extend({
notifications: Em.A()
// ....
//please see jsbin for the other stuff
})
This is picked up by a Collection view, which handles the actual rendering.
App.NotificationContainerView = Ember.CollectionView.extend({
contentBinding: 'controller.notifications'
// ....
//please see jsbin for the other stuff
});
As far as I currently understand how controllers work is that they depend on the currently active route and I so far haven't been able to put what currently is inside the ApplicationController into something more specific like a NotificationController. Is there a good way to do this? Or is this probably something I am just overthinking?
[1] http://aaron.haurwitz.com/#!/posts/growllike-notifications-with-emberjs
As described here [1], if render is used instead of the view helper, the appropriate controller is called as well. So, that actually seems to work: http://emberjs.jsbin.com/decojele/2/edit?html,js,console,output
[1] http://darthdeus.github.io/blog/2013/02/10/render-control-partial-view/

In an Ember view, what's the best way to run code after the rerendering of an internal child view?

I found a lot of questions about how to initialize jQuery plugins with dynamic data etc and usually the answer is that you should use the didInsertElement hook. My problem is that when using ember-data, initially the view is inserted empty and the template vars are filled afterwards through the bindings. Thus in didInsertElement the elements I need are not there.
I found a solution that works for me but I think there must be a better solution.
In addition to the didInsertElement method I also observe the attributes in the controller and call my code from there, too, wrapped in a Ember.run.next so the child view is rendered before.
Is there a better solution to react to updated child views?
It depends a bit on the size of your application, and the number of elements your view is rendering.
Edit: You might successfully observer the isLoaded property of the RecordArray. Some details here: https://github.com/emberjs/data/blob/master/packages/ember-data/lib/system/record_arrays/adapter_populated_record_array.js#L21
One option that I have used for views that have a single object as their content is something like:
MyApp.CustomView = Ember.View.extend({
content: null,
contentObserver: function() {
this.rerender();
}.observes('content')
}
If your view contents is a list, it makes little sense to re render the view for each item in the list, though.
However, I think this approach is fairly similar to what you are already doing, though.
Another approach is to implement your own adapter with Ember Data. This way, you can tell the rest of your application that it's finished loading your data. Something like:
MyApp.Adapter = DS.Adapter.create({
//Finding all object of a certain type. Fetching from the server
findAll: function(store, type, ids) {
var url = type.url;
jQuery.getJSON(url, function(data) {
store.loadMany(type, data);
});
//Perform some custom logic here...
}
}
This should work, but its not as generic as it should/could be though.
Also, you might want to take a look at this commit, which allows for registering a one-time event.
https://github.com/emberjs/ember.js/commit/1809e65012b93c0a530bfcb95eec22d972069745#L0R19
I had this problem and came up with a solution: make a handlebars helper that tells you when the sub-section has rendered. Hope that helps some other folks!