2013-02-07 112 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

相關問題