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

时间:2013-02-07 23:47:06

标签: javascript focus ember.js handlebars.js

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

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

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

控制器

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

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

有没有一个很好的方法来达到这个目的?我可以通过在模板中设置ID并使用jquery选择它来做一些hacky,但这看起来不够优雅。

2 个答案:

答案 0 :(得分:9)

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

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

Ember.TextSupport.reopen({
  attributeBindings: ["autofocus"]
});

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

{{view Ember.TextField autofocus="autofocus"}}

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

答案 1 :(得分:5)

考虑按如下方式扩展Ember.TextField:

App.FocusedTextField = Em.TextField.extend({
  didInsertElement: function() {
    this.$().focus();
  }
});

然后改变你的把手模板,改为使用它:

<script type="text/x-handlebars">
  {{#if isActive}}
    {{view App.FocusedTextField}}
  {{else}}
    <p {{action foo}}> Click Here to Enter text  </p>
  {{/if}}
</script>
相关问题