Skip to content

Instantly share code, notes, and snippets.

@pswai
Last active September 15, 2017 02:06
Show Gist options
  • Save pswai/59803287f0a988aecbb65c9d905025a5 to your computer and use it in GitHub Desktop.
Save pswai/59803287f0a988aecbb65c9d905025a5 to your computer and use it in GitHub Desktop.
Event objects in Ember
import Ember from 'ember';
export default Ember.Component.extend({
// Component-level event handler receives jQuery.Event
click(e) {
console.log('clickHookEvent', e);
},
actions: {
// {{action 'actionHelper'}} does not receive event
actionHelper(e) {
console.log('actionHelperEvent', e);
},
// onclick={{action 'closureAction'}} receives native Event
closureAction(e) {
console.log('closureActionEvent', e);
// It can be converted with `jQuery.event.fix`
// const fixedEvent = jQuery.event.fix(e);
// console.log('Fixed event', fixedEvent);
}
}
});
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
handle(e) {
console.log('Outside x-foo (application.hbs)', e);
}
}
});
Please check console for output.
There are 2 interesting things:
<ul>
<li>Different type of event handler receives different Event object (More in x-foo.js)</li>
<li>The sequence of actions being called (More in x-foo.hbs)</li>
</ul>
<p onclick={{action 'handle'}}>
{{x-foo}}
</p>
{{!-- Uncomment the follow to see ember-style sequence --}}
{{!--
<p {{action 'handle'}}>
{{x-foo}}
</p>
--}}
{{!-- Component-level handler (in JS) is called last --}}
{{!-- Native handler will be called first --}}
<div onclick={{action 'closureAction'}}>
{{!-- Normal {{action}} is called after all native handler --}}
<div {{action 'actionHelper'}}>Click me!</div>
</div>
{{!--
In short, the sequence when an event occurs:
1. Handlers for browser native hooks are triggered, bubbling all the way to root (<html>)
2. Handlers for ember-style actions are triggered, bubbling until the root of this component (in x-foo.js)
3. Component-level handlers are triggered (in x-foo.js)
4. Event bubbles to parent component, triggering ember-style handlers there. This occurs all the way until top ember component
--}}
{
"version": "0.12.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.3.2",
"ember-template-compiler": "2.3.2",
"ember-testing": "2.3.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment