我想显示输入字段,并在点击按钮后立即自动对焦。我仍然是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>
new-calendar component js
import Ember from 'ember';
export default Ember.Component.extend({
didInsertElement: function() {
this.$().focus();
}
});
当我点击按钮时,会显示文本字段,但是自动对焦并按下输入不起作用
答案 0 :(得分:6)
编写jQuery的方式,你试图将注意力集中在<div class="input-group">
上,试试这个:
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'
}}
这样,您可以在任何需要的地方重复使用焦点输入组件。
至于按Enter键来创建日历,我想你想听一下keyPress事件,检查它是否是回车键,然后发送动作而不是试图使用{{1} }。
insert-newline='createCalendar'
答案 1 :(得分:0)
尝试将焦点调用包装在Ember.run中,并安排它在after渲染队列中运行,如下所示:
didInsertElement: function()
{
Ember.run.scheduleOnce('afterRender', this, function() {
this.$().focus();
});
}
这篇博客文章帮助我理解了ember的生命周期钩子: http://madhatted.com/2013/6/8/lifecycle-hooks-in-ember-js-views