我想显示一个输入字段,并在单击按钮后立即自动对焦.我仍然是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}}
Run Code Online (Sandbox Code Playgroud)
新日历组件把手:
<div class="input-group">
{{input
class = 'form-control'
id = 'newCalendar'
type = 'text'
placeholder = 'New calendar'
value = calendarName
action = 'createCalendar'
}}
</div>
Run Code Online (Sandbox Code Playgroud)
新日历组件js
import Ember from 'ember';
export default Ember.Component.extend({
didInsertElement: function() {
this.$().focus();
}
});
Run Code Online (Sandbox Code Playgroud)
单击按钮时,将显示文本字段,但自动对焦和按下输入不起作用
编写jQuery的方式,你试图把重点放在<div class="input-group">
,改为:
didInsertElement: function() {
this.$('input').focus();
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是扩展Ember.TextField:
export default Ember.TextField.extend({
becomeFocused: function() {
this.$().focus();
}.on('didInsertElement')
});
Run Code Online (Sandbox Code Playgroud)
然后,在新日历模板中,使用此组件:
{{focus-input
class = 'form-control'
id = 'newCalendar'
type = 'text'
placeholder = 'New calendar'
value = calendarName
action = 'createCalendar'
}}
Run Code Online (Sandbox Code Playgroud)
这样,您可以在任何需要的地方重用焦点输入组件.
至于按Enter键来创建日历,我想你想要监听keyPress事件,检查它是否是回车键,然后发送动作而不是试图使用insert-newline='createCalendar'
.
//in FocusInputComponent
keyPress: function(e) {
// Return key.
if (e.keyCode === 13) {
this.sendAction();
}
}
Run Code Online (Sandbox Code Playgroud)