2013-02-07 110 views
2

我希望能够将焦点设置为一个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来选择它,但这看起来不够雅致。

回答

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> 
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

好的建议。对其他人的说明,此属性在Internet Explorer版本<10中不起作用。[Autofocus Attribute](http://www.w3schools.com/tags/att_input_autofocus.asp) – Scott

相关问题