When creating components, you can attach events to them. Let's take a look at an example of this.
student-info
:$ ember g component student-info
This will generate a component file in the component
directory and the templates/components
folder.
app/components/student-info.js
file. Add a new click
event:// app/components/student-info.js import Ember from 'ember'; const {$}= Ember export default Ember.Component.extend({ click() { $('html').fadeToggle( 'slow', 'linear'); $('html').delay(250).fadeIn(); } });
The first thing that you'll notice in this example is that we are using the ES2015 destructuring assignment. The destructuring assignment syntax extracts data from arrays or objects. Instead of typing Ember.$
everywhere, I can just type $
.
Ember CLI by default has jQuery installed. We are using the jQuery syntax to fade the HTML document and fade it back after the component is clicked.
We aren't limited to just the click
event though. There are several events that are available to Ember:
touchStart
touchMove
touchEnd
touchCancel
keyDown
keyUp
keyPress
mouseDown
mouseUp
contextMenu
click
doubleClick
mouseMove
focusIn
focusOut
mouseEnter
mouseLeave
submit
change
focusIn
focusOut
input
dragStart
drag
dragEnter
dragLeave
dragOver
dragEnd
drop
// app/templates/application.hbs <h2 id="title">Welcome to Ember</h2> {{#student-info}} Student info block {{/student-info}} {{outlet}}
The student-info
component is in block form. Click anywhere in the block to trigger the click
event and cause the HTML document to fade.
There is an index.html
file in the root of the app
folder. This file has the default HTML and head
tags. It also contains some links to your CSS and vendor files. You may notice that there are {{content-for}}
helpers. These are used with Ember add-ons and should not be deleted.
ember server
and the template should render as follows:The HTML document will fade if any part of the student info block div
is clicked.
Ember events in components work by adding the name of the event as a method in the component. These events are fired in the template that the component has been added to. Components, by default, are div
tags. So, any event that occurs must occur in the context of the div
tag in the template that is rendered.
Ember supports several different types of events, including double-clicking, HTML 5 drag and drop events, and touch events. Custom events can be registered using the Ember.Application.customEvents
method.