【问题标题】:ember autofocus component after insertion into DOM插入 DOM 后 ember 自动对焦组件
【发布时间】:2014-12-21 22:57:35
【问题描述】:

我想显示一个输入字段,并在单击按钮时立即自动对焦。我对 Ember 还是新手,所以我不确定这是正确的方法,但我尝试将其包装为 ember 组件

模板

{{#if showCalendarForm}}
  {{new-calendar focus-out='hideNewCalendar' insert-newline='createCalendar'}}
{{else}}
  <button class="btn btn-sm btn-primary" {{action "showNewCalendar"}}>New</button>
{{/if}}

新日历组件把手:

<div class="input-group">
  {{input
    class       = 'form-control'
    id          = 'newCalendar'
    type        = 'text'
    placeholder = 'New calendar'
    value       = calendarName
    action      = 'createCalendar'
  }}
</div>

新日历组件js

import Ember from 'ember';

export default Ember.Component.extend({
  didInsertElement: function() {
    this.$().focus();
  }
});

当我单击按钮时,会显示文本字段,但自动对焦和按 Enter 不起作用

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    jQuery 的编写方式,您试图将焦点设置在&lt;div class="input-group"&gt;,试试这个:

    didInsertElement: function() {
        this.$('input').focus();
    }
    

    另一种方法是扩展 Ember.TextField:

    export default Ember.TextField.extend({
      becomeFocused: function() {
        this.$().focus();
      }.on('didInsertElement')
    });
    

    然后,在你的新日历模板中,使用这个组件:

    {{focus-input
      class       = 'form-control'
      id          = 'newCalendar'
      type        = 'text'
      placeholder = 'New calendar'
      value       = calendarName
      action      = 'createCalendar'
    }}
    

    这样您就可以在任何需要的地方重用焦点输入组件。

    至于按回车创建日历,我想你想监听 keyPress 事件,检查是否是回车键,然后发送操作而不是尝试使用insert-newline='createCalendar'

    //in FocusInputComponent
    
    keyPress: function(e) {
      // Return key.
      if (e.keyCode === 13) {
        this.sendAction();
      }
    }
    

    【讨论】:

    • 第二种方法正是this ember cookbook recipe推荐的方法。
    • 这使自动对焦工作正常,但我仍然无法按回车键应用 createCalendar 功能
    【解决方案2】:

    尝试将焦点调用封装在 Ember.run 中,并安排它在渲染后队列中运行,如下所示:

    didInsertElement: function()
    {
        Ember.run.scheduleOnce('afterRender', this, function() {
            this.$().focus();
        });
    }
    

    这篇博文对我理解 ember 的生命周期钩子有很大帮助: http://madhatted.com/2013/6/8/lifecycle-hooks-in-ember-js-views

    【讨论】:

      猜你喜欢
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 2012-04-29
      • 2013-06-20
      相关资源
      最近更新 更多