Reputation: 4400
How does one target the element that an event occurred on in Ember? I thought the proper place for events was in a templates controller
but is that incorrect?
The error I am getting when I lick in a list-item is Uncaught TypeError: Cannot read property 'target' of undefined
Here is a fiddle to my code: http://jsfiddle.net/za1r2o5u/
Here is my JS:
App = Ember.Application.create();
var json_data = [
{"color": "red"},
{"color": "blue"}
];
App.Router.map(function() {
this.route("index", {path: '/'});
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return json_data;
}
});
App.IndexController = Ember.Controller.extend({
actions: {
clickMe: function(event) {
// How do I log the target element? This is throwing an error
console.log(event.target);
}
}
});
Here is my templates:
<script type="text/x-handlebars">
<h2> Welcome to Ember.js</h2>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<h2>Inside Index</h2>
<ul>
{{#each model}}
<li {{bind-attr class=color}} {{action 'clickMe'}}>Click here: {{color}}</li>
{{/each}}
</ul>
</script>
Upvotes: 0
Views: 1523
Reputation: 12694
Native event
objects from the DOM are available in view
and components
(subclasses of view):
http://jsfiddle.net/samselikoff/za1r2o5u/5/
As @torazaburo mentioned, for the purposes you're describing you probably don't want to do this. To "lazy load" data, in your template you'll have something like this
{{#each item in items}}
<!-- template markup -->
{{/each>>
and whenever items
is populated, the template will update. To update the items
data, you may use an action elsewhere in your template:
<button {{action 'getItems'}}>Get items</button>
and handle the action on your route:
//routes/some-route.js
export default Ember.Route.extend({
actions: {
getItems: function() {
var _this = this;
return Ember.$.getJSON('items', function(items) {
_this.controller.set('items', items);
}
}
}
});
then your template will update automatically.
Upvotes: 1