Ember:无法读取undefined的属性'target'

时间:2014-11-21 02:20:05

标签: javascript ember.js

如何定位Ember中发生事件的元素?我认为事件的正确位置是在controller模板中,但这是不正确的?

当我舔一个列表项时,我得到的错误是Uncaught TypeError: Cannot read property 'target' of undefined

以下是我的代码的小提琴: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>

1 个答案:

答案 0 :(得分:1)

来自DOM的本地event对象在viewcomponents(视图的子类)中可用:

http://jsfiddle.net/samselikoff/za1r2o5u/5/

正如@torazaburo所说,出于你描述的目的,你可能不想这样做。为了#懒惰负载&#34;数据,在您的模板中,您将拥有类似的内容

{{#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);
      }
    }
  }
});

然后您的模板会自动更新。