4

我正在学习 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 对其进行聚焦?

4

1 回答 1

9

有一个更好的方法来切换属性。

this.toggleProperty('propertyName');

还可以考虑使用 if/else。

{{#if isEditing}}
    {{input type="text" placeholder="Line item" class="my-input"}}
{{else}}
    <a href="#" {{action "toggleEditor"}}>{{value}}</a>
{{/if}}

我让它工作的方式是写一个这样的动作。

toggleIsEditing: function() {
        this.toggleProperty('isEditing');

        if(this.get('isEditing')) {
            Ember.run.scheduleOnce('afterRender', this, function() {
                $('.my-input').focus();
            });  
        }
},

奇怪的东西。

于 2016-04-08T10:12:26.230 回答