我正在学习 Ember 2,并尝试编写一个简单的内联编辑器。我的问题是自动聚焦输入元素。组件的模板如下:
{{#if isEditing}}
{{input type="text" placeholder="Line item" autofocus="autofocus" value=value class="form-control" focus-out="save"}}
{{/if}}
{{#unless isEditing}}
<a href="#" {{action "toggleEditor"}}>{{value}}</a>
{{/unless}}
控制器为:
import Ember from 'ember';
export default Ember.Component.extend({
actions: {
toggleEditor: function () {
this.set('isEditing', !this.get('isEditing'));
},
save: function () {
var object = this.get('object');
var property = this.get('property');
object.set(property, this.get('value'));
var promise = object.save();
promise.finally(() => {
this.send('toggleEditor');
});
}
}
});
将参数autofocus="autofocus"
设置isEditing
为 true 时使用。但是,当锚元素可见并且用户单击链接时,焦点不会转移到新可见的输入元素。因此,我的问题是:聚焦输入元素的最佳方式是什么?在里面toggleEditor
,如何通过 ID 访问输入元素以及如何使用 Ember 对其进行聚焦?