如何从组件中的Ember输入中捕获enter事件?

问题描述 投票:3回答:2

我有一个用于模式的Ember组件。模态通常包含表单,因此我在组件中使用keyPressed方法捕获各种事件,包括任何enter事件(键码13)。这将获取所有输入事件,但源于焦点{{input}}字段的事件除外。看起来Ember是deliberately blocking these events from bubbling,我可以从输入中捕获所有其他按键事件。

我一直无法找到一种干净的方法来从我的组件中捕获事件。我不想扩展任何东西,而是使用它,或者在特定的控制器上使用动作,或类似的东西,因为它们都感觉像是很肮脏的解决方法,对于某些应该很简单的事情,也似乎是一个显而易见的用例。我该怎么办?

编辑:小例子,以帮助澄清我的意思。我希望当用户在输入字段中按回车键时运行keyPressed

// Relevant section of component
App.MyModalComponent = Ember.Component.extend({
    // ...
    keyPressed: function (e) {
        if (e.which === 13) {
            console.log('Do something here, like submit the form');
        }
    },
    // ...
});

// Example of template
{{#my-modal}}
    <form>
        {{input value=foo}}
    </form>
{{/my-modal}}
forms ember.js dom-events event-bubbling
2个回答
3
投票

您是否在谈论keyPress,但我不认为keyPressed是受支持的事件(http://emberjs.com/guides/understanding-ember/the-view-layer/#toc_adding-new-events)。

App.MyModalComponent = Ember.Component.extend({
  foo:'component', 
    keyPress: function (e) {
      console.log('asdf');
        if (e.which === 13) {
            console.log('Do something here, like submit the form');
        }
    }
});

http://emberjs.jsbin.com/ciqomaqo/1/edit


1
投票

如果是用于提交表单,则使用浏览器的表单提交功能很有意义。您还可以使component元素本身成为一种形式:

Ember.Component.extend({
  tagName: 'form',
  submit: function(e) {
    e.preventDefault(); // To avoid page reload on event propagation
    // Do things
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.