如何定位 Ember 中发生事件的元素?我认为事件的正确位置是在模板 Controller
中,但这是不正确的吗?
当我点击列表项时遇到的错误是Uncaught TypeError: Cannot read property 'target' of undefined
这是我的代码的一个 fiddle :http://jsfiddle.net/za1r2o5u/
这是我的 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);
}
}
});
这是我的模板:
<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>
最佳答案
来自 DOM 的原生事件
对象可在 View
和组件
( View 的子类)中使用:
http://jsfiddle.net/samselikoff/za1r2o5u/5/
正如 @torazaburo 提到的,出于您所描述的目的,您可能不想这样做。要“延迟加载”数据,在您的模板中您将有类似这样的内容
{{#each item in items}}
<!-- template markup -->
{{/each>>
并且每当填充 items
时,模板都会更新。要更新 items
数据,您可以在模板中的其他位置使用操作:
<button {{action 'getItems'}}>Get items</button>
并处理路线上的操作:
//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);
}
}
}
});
然后您的模板将自动更新。
关于javascript - Ember : Cannot read property 'target' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27053115/