2

由于鼠标单击不在该任务区域中,我希望能够将焦点设置到文本区域。

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

<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,但这似乎不优雅。

4

2 回答 2

9

此外,为了减少看起来好像您正在将 jQuery 混合到您的 Ember 模块中的didInsertElementthis.$().focus();—— 这是我讨厌做的事情,您可以使用 Ember.JS 的方式为Ember.TextField.

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

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

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

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

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

于 2013-02-08T01:07:08.767 回答
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>
于 2013-02-08T00:19:31.657 回答