2012-02-27 77 views
10

我是新來Ember.js。 我希望把重點放在文本字段(樣品ID =「文本」)初始化後, 但功能齊全,不工作的重點方法...如何使用emberjs進行初始化後進行對焦?

<body> 
    <!-- library load --> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> 
    <script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.6.1.min.js"%3E%3C/script%3E'))</script> 
    <script src="http://cloud.github.com/downloads/emberjs/ember.js/ember-0.9.5.min.js"></script> 

    <script type="text/x-handlebars"> 
     {{view Em.TextField id="text"}} // want to focus it. 
    </script> 
    <script type="text/javascript"> 
    var App = Em.Application.create(); 
     App.ready = function() { 
      $('#text').focus(); // does'nt work. 
     } 
    </script> 
</body> 
+0

也http://stackoverflow.com/questions/12557584/how-to-use-autofocus-with-ember-js-templates/12560551#12560551見關於HTML5的解決方案。 – rit 2012-09-25 06:30:13

回答

12

下面的代碼不工作:

<script type="text/x-handlebars"> 
     {{view App.TextField id="text"}} // want to focus it. 
</script> 
<script type="text/javascript"> 
    var App = Em.Application.create(); 

    App.TextField = Em.TextField.extend({ 
    didInsertElement: function() { 
     this.$().focus(); 
    } 
    }); 
</script> 
+0

工作正常。謝謝! – arumons 2012-02-28 10:19:54

+1

有一種優雅的方式與[新的'{{輸入類型=「文本」}}'灰燼把手幫手(http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#做到這一點method_input)? – Abdull 2013-06-28 20:19:28

+0

我不這麼認爲,因爲視圖爲您創建的幕後。您可以使用JQuery訪問DOM元素,但它遠非優雅... – 2013-06-28 20:22:20

1

子類TextField然後蔓延定製View在你的模板顯得有點凌亂的我,所以我寫了這個小1KB包,可以讓你做到這一點更優雅,直接在模板中,沒有任何進一步的編碼:

<body> 
    <!-- all the libraries --> 
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
    <script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.min.js"></script> 
    <script src="http://cdnjs.cloudflare.com/ajax/libs/ember.js/1.2.0/ember.min.js"></script> 
    <script src="http://rawgithub.com/AndreasPizsa/ember-autofocus/master/dist/ember-autofocus.min.js"></script> 
    <!-- your template --> 
    <script type="text/x-handlebars"> 
    Hello, world! {{ input }} 
    : 
    : more elements here 
    : 
    {{ autofocus }} {# <<<<-- Magic happens here #} 
    </script> 
    <!-- your app --> 
    <script> 
    Ember.Application.create(); 
    </script> 
</body> 

你可以從https://github.com/AndreasPizsa/ember-autofocusbower install ember-autofocus得到它。我很感激反饋!

相關問題