Correct way to handle inter-controller relationships with Ember.js - ember.js

I have an application scheme implemented in Ember that basically follows this layout:
The concept is that the user can interact with features on the Map View (which is always present) and basic navigation occurs between various views in the Parent View and an arbitrary stack of Sub Views. The user can create new features on the map, edit existing ones etc.
The URL for a particular feature could be /features/123/edit
Since input into my interaction panels is very much dependent on interaction with the Map View (drawing a polygon, placing a marker etc.) my controllers for these views are setup to "need" the Map Controller. When a particular panel view is present interaction with the map should affect the panels in various ways.
My question is - how does one scale such tight controller coupling? I essentially need to switch between different Map modes based on which panel is currently active. I also, I believe, need to observe events on the map and act upon such events depending on the current active panel.
I setup a proof of concept where a certain Sub View Controller observes certain properties of the Map Controller (with for example .observes("controllers.map.activecoords") however, such an observer will continue to trigger even after the user has navigated away from the particular Sub view (i.e. as soon as the controller has been initialised). Must I setup and tear down such observers manually (i.e. using addObserver) when entering and leaving the route? Is this the right pattern? I've gotten the impression that requires that I manually remove all such observers during transitions to avoid unexpected behaviour and memory leaks.
Perhaps I'm going about this completely the wrong way? Are there any others patterns that fits my use case with an always present map with different states and intercommunication with interaction panels?

Perhaps the architecture of your application shouldn't be connecting controllers, but rather ask yourself "What is the model here, really?"
In each case, I think the model is your map, or at least its "contents". The features are really decorating the interaction with your central model, which is the map, underlying it all.
So really you have a single model here. You effectively have a map resource, and many feature routes on that resource, viewed from the URL/API.
The question is now not so much "how to manage a dependency hierarchy between controllers?" as "how do I manage a view and a subview on the same model?" which is answered quite simply in the standard ember nested route. Your outer view is always present and it has an outlet which is where your feature goes. How it's rendered is the inverse of how the standard nested route is rendered, but nevertheless it's the same pattern.
So, the TL;DR answer is... go through your model and the routes... use them to talk about your common data: the model is, afterall, your data, and the controllers and views are simply augmenting and enabling the user experience, presentation and interaction of them.
Most of these sorts of architectural problems can be resolved by moving the data up and down the hierarchy (template view / component / controller / route / model) until you find a place which is low enough to still be accessible to objects that need access to it, yet high enough that it makes sense by not being tightly bound with too many things, but still is in the right spot and "feels right".
If it's too high, you'll tend to be doing the wrong kind of work with your objects (ie controllers should not be mucking with view mechanics, models shouldn't really have presentation stuff in them, etc.
If it's too low, you'll tend to be doing too much work with the framework and you'll tend to be repeating yourself a lot... ie controllers will be doing a lot of work to get the data they need, for example.

Related

testing a component with complex angular components nested inside using PageObjects

Our Application has components which consume components with consume components of varying complexity. So i just want the input on the page, to validate when an object is set that the text is correct. The issue is that it is one of these subcomponents.
My colleague told me that there is 2 ways to do this, The first is to use Page Objects, and Chaining annotation to find it on my page, and then find the next id etc until my input is found. It requires me to look through another teams' Component Markup to narrow it down to the input i want to leverage. I dont believe I should have to go into another component definition, or a definition of a definition to get the appropriate chain to get this arbitrary input. It starts to create issues where if a lateral team creates changes unbeknownst to me, my PO will be broken.
The other option my friend asked was to use fixture.query to find the component. This would be as simple as:
fixture.query((el)=> el.attribute["id"] == "description",
(comp){
expect(comp.value, value);
});`
Using Query looks at the markup but then will automatically componentize it as the appropriate SubComponent. In this case, comp.value is the value stored in the HTML. So, if i did something like:
fixture.update((MainComponent comp) {
comp.myinput.value = new Foo();
});
Then I am setting and getting this programmatically, so i am a bit unsure if it properly would reflect what is on the screen.
Whats the best course of action? It seems PO would be better, but im not sure if there is a way around having to deep query for input boxes outside of the component i am testing.
Thanks
I don't think I have a definitive answer for you but I can tell you how we do it at Google. For pretty much any component we provide the page object alongside the component. This is twofold it is for testing that widget, and also so we can have this as a shareable resource for other tests.
For leaf widgets the page objects are a little less fleshed out and are really just there for the local test. For components that are shared heavily the page object is a bit more flushed out for reusability. Without this much of the API for the widget (html, css, etc) we would need to consider public and changes to them would be very hard (person responsible for making the public breaking change needs to fix all associated code.) With it we can have a contract to only support the page object API and html structure changes are not considered breaking changes. At times we have even gone so far as to have two page objects for a widget. One for the local test, and one to share. Sometimes the API you want to expose for a local test is much more than you want people to use themselves.
We can then compose these page objects into higher level page objects that represent the widget. Good page objects support a higher level of abstraction for that widget. For example a calendar widget would let you go to the next/previous month, get the current selected date, etc. rather than directly exposing the buttons/inputs that accomplish those actions.
We plan to expose these page objects for angular_components eventually, but we are currently working on how to expose these. Our internal package structure is different than what we have externally. We have many packages per individual widget (page_objects, examples, widget itself) and we need to reconcile this externally before we expose them.
Here is an example:
import 'package:pageloader/objects.dart';
import 'material_button_po.dart';
/// Webdriver page object for `material-yes-no-buttons` component.
#EnsureTag('material-yes-no-buttons')
class MaterialYesNoButtonsPO {
#ByClass('btn-yes')
#optional
MaterialButtonPO yesButton;
#ByClass('btn-no')
#optional
MaterialButtonPO noButton;
}

When should I use controllers vs routes in EmberJS?

I know this question might seem a little duplicate but the other version of this question is old and some of the content (such as Views) aren't even a part of ember anymore.
I'm about 4 weeks into my internship as a front-end developer working with EmberJS. I still don't understand when it's better to use the route over the controller or vice-versa. It seems to me that every action in the route can also be used in the controller.
The one recent thing I heard was that ember routes should be stateless where as controllers should be stateful.
What is the current state of controllers and routes. When should one be used over the other?
Consider the following example to understand the state of a controller (or route, or anything), in simple terms and in current context -- lets say you have a page (like a form) with three tabs; each tab can be considered as a state - it would call different components based on the state (or the tab you are in). Now if you would happen to go back for some reason, and hit the form link again, you would see that the state would remain the same. (if you were on tab 2 when you hit back, on returning to the form, you would still be on tab 2).
So to maintain these states, controllers are the way to go, since they are singletons. Route would have lost that information, and started fresh. So basically your variables/objects in a controller would define the 'state'.
Route-actions can be as easily used as controller actions- see https://github.com/DockYard/ember-route-action-helper. So if your template for this route is just using model as the object directly, and you don't need to maintain the 'state', you can pretty much do without your controller.
But if your template was using variables which needed manipulation, you would need controller.
Hope this helps!

Where to store transient UI state in Ember 2.0

Ember 2.0 has gone great lengths towards making everything a component. With routable components coming soon, controllers will probably phased out as well.
Context
However, there is a recurring problem I face when building User interface, which I don't have a satisfying pattern for so far: user interface state.
What am I taking about?
Selection state
Current focus
Folded/unfolded state in some tree display
Basically, any state that is not part of the actual data, yet has to be tracked on an object-by-object basis. In the past, this used to be done with Controllers, acting as proxies to models. This approach is now obsolete. The new approach is Components everywhere, for the better. Component does the bookkeeping, tracks transient state and you get actions back.
A typical pattern I have, though, is with shared state, such as a list with selectable items.
The issue
Building a list component, with the following requirements:
Each item can be selected.
Selection state changes the DOM (some class bindings).
User can draw a rectangle in the list component to select several items at once.
Ideally, the whole behavior can be abstracted out as a mixin.
Question: where does the selection flag live?
Attempts
1) Everything is a component.
I make each item a sub-component, say {{my-list-item}}. The component tracks the selection state. Problem: how can the list component update the selection state?
2) Move state out of sub-components.
Put it on the list component. Within a separate state array alongside the item list. Pros: the list has all the state it needs. Cons: it's a nightmare to keep it synced when items are added or removed from the list. And it means the sub-component have no access to the state. Or maybe I could pass it to them as a bound value?
3) Reintroducing proxies.
Coming to think of it, there is a way to share some state: put it on the models. Well, not on the actual models so as not to pollute them with local state, but by setting up an ArrayProxy that will return some ObjectProxy for every item, to hold the state.
Pros: this is the only solution I managed to implement completely. Cons: encapsulation and decapsulation of items is a hassle. Also, after a few layers of being passed around, get and set have to go through 4 ou 5 proxies, which I fear will be a problem with performance.
Also, it does not work well for mixins. Should I want to abstract out some HasSelection mixin, and a HasFoldableItems mixin, and a Sortable mixin, they all need some state.
Back to the drawing board
Is there some better pattern I have not found?
I found the following relevant questions, but that led me nowhere:
Ember.js - where should interface state be stored? (2012, suggests something close to my #3 above)
Road to Ember 2.0 - High level Ember app structure feedback? (some of the key questions in the list are relevant to this one)
Great question - I actually went to one of the core ember team members to find out and the answer currently is services. Because the component is best left stateless (for the most part) you can leverage a service to persist this state that doesn't fit into a server persisted model.
Here is a great example that Stef Penner put together showing how you might save a "email draft" in your ember app (that isn't persisted backend)
https://github.com/stefanpenner/ember-state-services
Example component for reference (from the github project above)
export default Ember.Component.extend({
tagName: 'form',
editEmailService: Ember.inject.service('email-edit'),
state: Ember.computed('email', function() {
return this.editEmailService.stateFor(this.get('email'));
}).readOnly(),
actions: {
save() {
this.get('state').applyChanges();
this.sendAction('on-save', this.get('email'));
},
cancel() {
this.get('state').discardChanges();
this.sendAction('on-cancel', this.get('email'));
}
}
});

When to use which controller type?

I seem to be getting more and more confounded at what appears, on the surface at least to be pretty basic architectural questions regarding building ember apps.
Which Controller type?
In the last month or so, I've seen people implement controllers through Ember.Controller, Ember.ArrayController, Ember.ObjectController, and Ember.ArrayProxy. Removing ArrayController and ArrayProxy (due to them being identical), what are common use cases between each type?
So far, i've been able to gather that:
ArrayControllers/Proxies should be used when you have n elements within the view you intend to control
ObjectControllers should be used when the view is simple enough to maintain it's state in a single object, or be a single instance of a model's object.
Controllers --- ? No idea.
What are some basic differences between the controller types? There doesn't seem to be concrete information on when to use which, and for which use case. The API docs are good at telling me the nitty gritty of each of them, but not WHEN to use each.
The relationship between a View and a Controller can be baffling
When a View is connected via a routes ConnectOutlets function call, what exactly happens between the controller and the view?
Are events tied into the view itself (which seems to be the case) and if so, where on earth do you interact with the controller singleton to perform CRUD-esq things on its properties? this.get('controllerName') doesn't seem to do the trick, and nearly each post or tutorial or code sample out there does this a different way.
Models that aren't
I realize that Ember Data looks to help solve some of the more irritating parts of dealing with data and keeping it in sync, but at a larger perspective, in the concept of "MVC", ember doesn't really seem to have a Model of any kind. It's just some object that gets subclassed from a specific thing and then tracked....somewhere? Somehow? Magical?
#trek sufficed that an Ember.Object could manage ajax'ing data and handling state on the client just fine, but if you look at something like the todomvc.com ember app, it uses a localStorage paradigm that is COMPLETELY different in implementation then everything i've looked at.
How EXACTLY should the 'Model' part of the MVC equation be done here?
Views make me want to murder children
There seems to be a significant number of ways to construct a "view" in terms of displaying markup to a user.
ContainerViews, using subviews / childviews
nested outlets
Handlebars templates + an outlet
using #each foo in controller
Injection through literals (template: Ember.Handlebars.compile('<h1>foo</h1>') etc)
With that in mind, what's the 'proper' way to build modular UI components with ember? This more than anything is a major pain point for the adoption of this framework for me.
I love the direction that Ember is going with application development on the web. The concepts seem simple, but the verbosity is that of Objective-C (which makes sense given it's lineage) but I swear to god I feel like i'm fighting the god damned framework more than i'm actually working on my application. The verbosity of the syntax and the lack of structured documentation outside of API documentation (which lets face it, 300k of javascript is a significant amount of code to throw some breakpoints down and try to debug your issues).
I realize the challenge that you guys are up against, but hopefully this at least makes you pause for a minute and think of how you could make life easier for the incoming developer who's worked with other frameworks (or hell, even worked within an MVC framework, like rails or django or backbone or angular) and say "this is how we think ember should be used".
Take some of the opinionated software design decisions and apply them toward the community. We'll do nothing but be cheerleaders for you if you do it, promise.
Please don't hurt any children. AFAIK the ember-core team are all over 18, so any ember-view-related frustration is clearly better directed towards adults. With that in mind...
Which Controller Type?
You've got the "what" right, but maybe missing the "why". Controller can be a little misleading, especially coming from rails. Think of these controller singletons as representing the state (in-memory) of your application.
Which kind of controller to use depends on what is required for that part of your application. For example, a back-of-napkin sketch for any app might have a topnav, postList, postDetails section. In ember, each is represented by one or more view/controller pairs. In this app I would expect to see ApplicationController and NavigationController extending Ember.Controler while postList would extend ArrayController and PostDetails would be an ObjectController.
You could do it all using just Ember.Controller but ObjectController and ArrayController are really useful for wrapping model data. Any non-trivial ember app will probably use all three.
The relationship between a View and a Controller
A controller's job is to provide the context in which the view will be rendered. Ideally you'd like to keep logic out of views, so a typical controller will have lots of computed properties to do things like:
transform data from the underlying model objects
sort/filter/select a list of objects
reflect application state
whats the deal with connectOutlets? This is where you should be using the requested route/context to decide which views/data should be plugged into the outlets of your application. The controller's connectOutlet method has a bunch of magic to make it easy, but maybe too much magic. What happens (afaik) when you call: parentcontroller.connectOutlet 'child' is
Ember creates an instance of ChildView
The {{outlet}} handlebars helper in parentController's view is bound to this childView instance
The childView is rendered with the router.childController singleton as it's context
where to do crud stuff?: Typically in an action on the router. This seems crazy at first. Think of ember router not like rails but as a stateManager that just happens to also handle routing. In near-future router API will change to make this more clear. Anyway, use router actions to do things like create model instances, commit/rollback transactions and trigger state change. This is easy to do if you use the handlebars {{action}} helper for links/buttons as it targets the router by default.
Views on the other hand should have logic for "reacting to browser events" - that means really low-level stuff like show/hide something on mouseover or integrate with 3rd party libraries to do effects and animations.
You might find this screencast helpful in understanding how to do CRUD-esq things:
http://blog.bigbinary.com/2012/09/06/crud-application-in-emberjs.html
Models WTF?
Agreed in Ember any object could be used as a 'Model'. I think #trek does a good job of demonstrating how one might accomplish this via Ember.Object. This works great for a simple app, and six months back maybe would've been your best bet as ember-data was really immature. I'm not clear on the history of ember's todomvc app, but for sure it was written months ago. For sure it should be updated, but meantime I'd not recommend using it to learn about current ember best-practices.
Instead, you should go with ember-data. Over the last few months it has really evolved and should be the default choice for any new, non-trivial ember app. #tomdale just gave a great presentation on this topic, I'd recommend having a look: https://speakerdeck.com/tomdale/ember-data-internals
what's the 'proper' way to build modular UI components with ember?
For building modular UI components:
ContainerViews, using subviews / childviews
Injection through literals (template: Ember.Handlebars.compile ...)
For building an individual application:
nested outlets
Handlebars templates + an outlet
using #each foo in controller
Building modular UI components is a totally different problem than building an application. Ember.View and it's subclasses were designed for this purpose. You can easily extend/combine them to compose widgets with custom behaviors and share those widgets across applications.
At least that's how i've seen it done. If they are for internal use could also reference handlebars templates instead of object literals, but if planning to distribute the object literals approach seems best.
A great real-world example of this is the ember-bootstrap project. I learned a lot about working with ember-views by reading through that project's source. http://emberjs-addons.github.com/ember-bootstrap/
TLDR
Pick controller that maps to type of data being represented
Controllers provide context for the view and remember application state
Use ember data for your models
Use subclasses of Ember.View to make components
Be nice to children

Concerning the Typical Behavior of Controllers in Ember

Are controllers in ember.js meant to be tied to main view areas/scenes a la iOS, or more tied to a set of data?
Is it common/wise to have several main views tied to the same controller in ember?
In iOS main portions or sections of the screen are tied to a single controller. If you want to present another main interface, say a modal window to create a new element, you (typically) have an entirely separate controller to manage that view and its data/logic.
In something like Zend Framework, you have controllers that might perform some common spinup steps of ensuring authentication, but largely the actions play the role that controllers do in iOS, handling the logic and providing the data for 1 main section or view (being the web, this usually ends up being the whole page).
What is that typical role or advised pattern for using controllers in ember?
You have a couple different questions here so I'll address them one at a time.
First, you asked if controllers should be data oriented or view oriented. In my experience both behaviors are allowable. Controllers are an excellent way to manage data sets for your application, including things like filtering and searching. Evin Grano wrote a good post about this from the SproutCore perspective and most of the concepts should apply to Ember as well: http://www.itsgotwhatplantscrave.com/2009/07/30/root-controller-paradigm/. Controllers are also well suited for controlling the application state and behavior. For example, you might put a method in a controller that is bound to as a button action elsewhere in your app. However, you should also examine Ember States to see if these might be better suited to your scenario.
Secondly, you asked about tying multiple views to the same controller. Personally, I see no concerns with this as long as the controller maintains a distinct purpose. If the views are logically related and share in the same state or data then a single controller makes sense. If you find the controller growing to cover too many different areas, you should consider splitting it into multiple controllers.
From my limited experience in Ember.js, I have regulate to the following:
The view handles user actions related to changes in the presentation layer, limited to its own instance.
A navigation controller/statemanager handles complex manipulation of what is presented (add multiple views, remove some other, etc.).
The controller responds to user actions related to the data layer.