在焦点应用程序中设置焦点

Bos*_*ohn 2 javascript focus handlebars.js ember.js

我希望能够将焦点设置为textarea,因为鼠标单击不在该任务区域中.

作为一个最小的例子,假设我从一个文本开始,如果你点击它,它将被替换为文本字段.我可以通过一个把手脚本实现这个目标:

<script type="text/x-handlebars">
  {{#if isActive}}
  {{view Ember.TextField}}
  {{else}}
  <p {{action foo}}> Click Here to Enter text  </p>
  {{/if}}
</script>
Run Code Online (Sandbox Code Playgroud)

与控制器

App.ApplicationController = Ember.Controller.extend({
    isActive: false,
    foo: function(){
       this.set("isActive", true);
    }
});
Run Code Online (Sandbox Code Playgroud)

这适用于在单击时创建文本字段,但不会将焦点放在该文本区域上(只需单击二次即可实际输入文本).

有没有一个很好的方法来实现这一目标?我可以通过在模板中设置ID并使用jquery选择它来做一些hacky,但这似乎不够优雅.

Wil*_*ney 9

此外,为了减少didInsertElement并且this.$().focus();看起来好像你正在将jQuery混合到你的Ember模块中 - 以及我讨厌做的事情,你可以使用Ember.JS方法来指定其他属性Ember.TextField.

我们可以指定我们对HTML5 autofocus属性感兴趣:

Ember.TextSupport.reopen({
  attributeBindings: ["autofocus"]
});
Run Code Online (Sandbox Code Playgroud)

然后我们可以将标准Ember.TextField放在我们的页面上,而不必创建另一个视图来扩展Ember.TextField:

{{view Ember.TextField autofocus="autofocus"}}
Run Code Online (Sandbox Code Playgroud)

见JSFiddle:http://jsfiddle.net/MdzhN/


Mik*_*tti 5

考虑如下扩展Ember.TextField:

App.FocusedTextField = Em.TextField.extend({
  didInsertElement: function() {
    this.$().focus();
  }
});
Run Code Online (Sandbox Code Playgroud)

然后更改您的把手模板以使用它:

<script type="text/x-handlebars">
  {{#if isActive}}
    {{view App.FocusedTextField}}
  {{else}}
    <p {{action foo}}> Click Here to Enter text  </p>
  {{/if}}
</script>
Run Code Online (Sandbox Code Playgroud)