javascript - Ember : Cannot read property 'target' of undefined

标签 javascript ember.js

如何定位 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/

相关文章:

ember.js - 使用 {{#each ...} 时,{{action ...}} 未设置 event.context(未定义)

ember.js - Ember CLI - 在 route 使用 moment.js 时出错

javascript - 模型、命名和这个

ember.js - ember 构建完成后移动输出文件

javascript - 通过删除 javascript 中的重复项来组合对象数组

javascript - 分配 html 表单输入一个 JS 变量

javascript - 在命令行脚本中包含没有 HTML 或 DOM 的 JS 文件中的 Javascript 文件

javascript - 断言失败 : The value that #each loops over must be an Array. 你通过了 [object Object]

javascript - 如何在不刷新页面的情况下,点击按钮后显示本地存储的内容?

javascript - Node 跨 3 个文件导出