I'm trying to implement an action on a controller and get the warning:
DEPRECATION: Action handlers implemented directly on controllers are deprecated in favor of action handlers on an actions object
If I use Em.ObjectController.create(), when I click my button I get a warning stating that actions must be provided at extend time. However, if I use Em.ObjectController.extend(), when I click the button I get an error saying the action did not exist on the controller.
I created a jsBin to view this
//App.ToolbarController = Ember.ObjectController.create({
App.ToolbarController = Ember.ObjectController.extend({
model: { fu: "baar" },
actions: {
doSomethingUseful: function(data) {
console.log("doing nothing useful...");
}
}
});
I took a look at your jsBin
First off in the future its easier to debug your templates if you post them as an embedded script tag instead of the compiled handlebars function.
I've made a bin that fixes your issue.
I believe your issue had to do with the method you were using to create your view.
{{view App.ToolbarView controllerBinding="App.ToolbarController"}}
I'm not sure if that works properly.
Instead you should use the render helper
{{ render 'toolbar' }}
That way ember will try to find the toolbar view, controller and template and wire them all together properly.
Related
Cannot get my head around the following problem. I got a Uncaught TypeError: Cannot read property 'send' of undefined whatever I try. I think it must be the controllerBinding in the itemsViewClass, however I think it is defined correctly.
In the code below there are two showMenu actions. The first one works, but the last one in the itemsViewClass does not.
Please take a look at my code below (I show only the relevant code):
//views/menu.js
import Ember from "ember";
var MenuitemsView = Ember.View.extend({
template: Ember.Handlebars.compile('<div{{action "showMenu" target="view"}}>this works already</div>\
much more code here'),
contentBinding: 'content',
itemsView: Ember.CollectionView.extend({
contentBinding: 'parentView.subCategories',
itemViewClass: Ember.View.extend({
controllerBinding: 'view.parentView.controller', // tried to add controllerBinding but did not help
// this is where the question is all about
template: Ember.Handlebars.compile('<div {{action "showMenu" target="parentView"}}>dummy</div>')
}),
actions: {
showMenu: function(){
// dummy for testing
console.log('showmenu itemsView');
}
}
}),
actions: {
showMenu: function() {
console.log('showMenu parentView!'); // how to reach this action?
}
}
});
export default MenuitemsView;
I have tested with {{action "showMenu" target="view"}} and without a target. It seems not to help.
Do someone have a clue why the second showMenu action cannot be reached?
OK, so this is by no means the only way to do logic separation in Ember, but it's the method I use, and seems to be the method generally used in the examples across the web.
The idea is to think of events and actions as separate logic pools, where an event is some manipulation of the DOM itself, and an action is a translatable function that modifies the underlying logic of the application in some way.
Therefore, the flow would look something like this:
Template -> (User Clicks) -> View[click event] -> (sends action to) -> Controller[handleLogic]
The views and the controllers are only loosely connected (which is why you can't directly access views from controllers), so you would need to bind a controller to a view so that you could access it to perform an action.
I have a jsfiddle which gives you an idea of how to use nested views/controllers in this way:
jsfiddle
If you look at the Javascript for that fiddle, it shows that if you use the view/controller separation, you can specifically target controllers to use their actions, utilising the needs keyword within the controller. This is demonstrated in the LevelTwoEntryController in the fiddle.
At an overview level, what should happen if your bindings are correct, is that you perform an action on the template (either by using a click event handler in the view, or using an {{action}} helper in the template itself, which sends the action to the controller for that template. Which controller that is will depend on how your bindings and routing are set up (i've seen it where I've created a view with a template inside a containerView, but the controller is for the containerView itself, not the child view). If the action is not found within that controller, it will then bubble up to the router itself (not the parent controller), and the router is given a chance to handle the action. If you need to hit a controller action at a different level (such as a parent controller or sibling), you use the needs keyword within the controller (see the fiddle).
I hope i've explained this in an understandable way. The view/controller logic separation and loose coupling confused me for a long time in Ember. What this explaination doesn't do, is explain why you are able to use action handlers in your view, as I didn't even know that was possible :(
I have an app with many similar views which I instantiate programmatically to "DRY-up" my app.
The problem is that controllers instantiated programmatically do not delegate actions in the actions hash further. This is clear because there is nothing from which the controller can derive the hierarchy. There should be a way, however, to tell a controller which parent controller it has to use for event bubbling. Does anyone know it?
You shouldn't be initializing controller's on your own. All controller initialization should be handled by Ember itself. Another interesting note, controller's are intended to be singletons in the application. The only exception to this being the itemController when looping over an ArrayController. You can read more about it in the guides. Quote from the guides:
In Ember.js applications, you will always specify your controllers as
classes, and the framework is responsible for instantiating them and
providing them to your templates.
This makes it super-simple to test your controllers, and ensures that
your entire application shares a single instance of each controller.
Update 1:
An example of how to do routing for a wizard:
App.Router.map(function() {
this.resource('wizard', function() {
this.route('step1');
this.route('step2');
this.route('step3');
});
});
This way, you can have a separate controller/view/template per step of the wizard. If you have logic around how much of each step should be completed prior to transitioning to the next one, you can handle that in the individual routes.
Update 2:
In the event that the number of steps aren't predetermined, but are based on the data being fed to the app, you can make a WizardController that is an ArrayController where each item in the array is a step in the wizard. Then, use the lookupItemController hook on the ArrayController, kind of like this:
App.WizardRoute = Ember.Route.extend({
model: function() {
return [
{controllerName: 'step1', templateName: 'step1'},
{controllerName: 'step2', templateName: 'step2'},
{controllerName: 'step3', templateName: 'step3'}
];
}
});
App.WizardController = Ember.ArrayController.extend({
lookupItemController: function(modelObject) {
return modelObject.controllerName;
}
});
{{#each step in controller}}
{{view Ember.View templateName=step.templateName}}
{{/each}}
As another, probably better, alternative, you can override the renderTemplate hook in the route where you're pulling down the model for the next step in the wizard and pass in the appropriate templateName and controller in the render call, kind of like you see here.
Point being, I think it should be possible to do this without having to instantiate controllers yourself.
I guess I'm missing something really basic, but the following fails with The action 'login' did not exist on App.AppController.
Template:
<h2>Click the button and watch the console</h2>
<button type="button" {{action login target="App.AppController"}}>Log in</button>
Controller:
App.AppController = Ember.Controller.extend({
login: function() {
// never gets here
debugger;
},
send: function() {
// or even here
debugger;
}
});
JSBin: http://jsbin.com/okuqiv/5/edit (this is pointing to Ember latest, but it's the same behavior with 1.0-rc2, the version I've been using for a couple of days; I haven't tried it on previous versions).
Upon debugging, it seems that somehow the controller mixin is not exposing all the functions it should -- login() is a function I added, but send() is an Ember function. It's also missing other functions like get().
I saw that in my app the login() function exists on the object App.AppController.prototype, while in the JSBin it exists on one of the objects in the mixin chain.
At this point I'd even be happy to handle the login action in the view, or the router (as it seems it was the default in the past), but none of those seem to work.
From the documentation, the current default place where the actions handlers should live is the controller anyway, and then the routes, but if I remove the target and add login() to the route, I get another error: Nothing handled the event 'login' (I'm using the target in the first place because in my app /login is a separate route and has a different controller).
Solutions and workaround will be very appreciated!
You are targeting the class App.AppController and not an actual instance of that class. If you are using the router and are in an app view then action would target the appController by default.
I've updated the JSbin to call login on the IndexController since your example is in the index route:
http://jsbin.com/okuqiv/10/
You were also over riding the send method which was preventing login from being called.
In my app using Emberjs, every action gets triggered 3 times on a single click.
For example with the following template and view:
Template:
<button {{action "removeFoo"}}>remove</button>
View with click handler:
listsView = Ember.View.create({
templateName: 'lists',
removeFoo: function(event) {
event.preventDefault();
console.log(new Date().valueOf());
}
})
I get the following 3 outputs in the console:
1333634360209
1333634360215
1333634360217
Does anybody know what's causing this or what's the best approach to debug the problem?
The actual problem was, that the Ember app was part of a Rails application which had two other Ember apps already. Those Ember apps didn't have a rootElement specified. Adding a rootElement for every Ember app fixed the problem.
I'm not sure why it's being called multiple times, but are you intentionally overriding Ember.View#remove? If so you'll probably want to call this._super() so that it destroys the element etc...
Here's the definition of it in the source:
https://github.com/emberjs/ember.js/blob/master/packages/ember-views/lib/views/view.js#L770
If that wasn't your intention, you might want to call your action something else and see if resolves the problem.
Using the latest Ember.js version 0.9.6 works fine, see http://jsfiddle.net/pangratz666/BxccU/
How do I run a function after an Ember View is inserted into the DOM?
Here's my use-case: I'd like to use jQuery UI sortable to allow sorting.
You need to override didInsertElement as it's "Called when the element of the view has been inserted into the DOM. Override this function to do any set up that requires an element in the document body."
Inside the didInsertElement callback, you can use this.$() to get a jQuery object for the view's element.
Reference: https://github.com/emberjs/ember.js/blob/master/packages/ember-views/lib/views/view.js
You can also use afterRender method
didInsertElement: function () {
Ember.run.scheduleOnce('afterRender', this, function () {
//Put your code here what you want to do after render of a view
});
}
Ember 2.x: View is deprecated, use component instead
You have to understand the component's lifecycle to know when does certain things happen.
As components are rendered, re-rendered and finally removed, Ember provides lifecycle hooks that allow you to run code at specific times in a component's life.
https://guides.emberjs.com/v2.6.0/components/the-component-lifecycle/
Generally, didInsertElement is a great place to integrate with 3rd-party libraries.
This hook guarantees two (2) things,
The component's element has been both created and inserted into the DOM.
The component's element is accessible via the component's $() method.
In you need JavaScript to run whenever the attributes change
Run your code inside didRender hook.
Once again, please read the lifecycle documentation above for more information
Starting with Ember 3.13, you can use components that inherit from Glimmer, and this example below shows what that could look like:
import Component from '#glimmer/component';
import { action } from '#ember/object';
/* global jQuery */
export default class MyOctaneComponent extends Component {
#action configureSorting(element) {
jQuery(element).sortable();
}
}
<div {{did-insert this.configureSorting}}>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
These view style components don't have lifecycle hooks directly, instead, you can use render-modifiers to attach a function. Unofficial introduction to modifiers can be found here
The benefit of this is that, it's clearer what the responsibilities of the template are and become.
Here is a runnable codesandbox if you want to play around with this:
https://codesandbox.io/s/octane-starter-ftt8s
You need to fire whatever you want in the didInsertElement callback in your View:
MyEmberApp.PostsIndexView = Ember.View.extend({
didInsertElement: function(){
// 'this' refers to the view's template element.
this.$('table.has-datatable').DataTable();
}
});