2012-02-27 21 views
10

Tôi mới sử dụng Ember.js. tôi muốn tập trung vào TextField (trong mẫu, id = "text") sau khi khởi tạo, nhưng trong chức năng sẵn sàng, không hoạt động phương pháp tập trung ...Làm thế nào để tập trung sau khi khởi tạo với 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

Xem thêm http://stackoverflow.com/questions/12557584/how-to-use-autofocus-with-ember-js-templates/12560551#12560551 về giải pháp với HTML5. – rit

Trả lời

12

Các mã sau đây làm việc:

<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

hoạt động tốt. cám ơn! – arumons

+1

Có cách nào thanh lịch để làm điều này với [new '{{input type =" text "}}' helper Helpbars Ember] (http://emberjs.com/api/classes/Ember.Handlebars.helpers.html# method_input)? – Abdull

+0

Tôi không nghĩ vậy, vì chế độ xem được tạo cho bạn phía sau cảnh. Bạn có thể truy cập vào phần tử DOM bằng cách sử dụng JQuery, nhưng nó không phải là thanh lịch ... –

1

Tạo subclass TextField và sau đó lây lan một tùy chỉnh View xung quanh các mẫu của bạn có vẻ hơi lộn xộn với tôi, vì vậy tôi đã viết này gói 1kb nhỏ cho phép bạn làm điều này tao nhã hơn, trực tiếp trong các mẫu, mà không cần bất kỳ mã hóa thêm:

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

Bạn có thể tải xuống từ https://github.com/AndreasPizsa/ember-autofocus hoặc với bower install ember-autofocus. Tôi đánh giá cao phản hồi!

Các vấn đề liên quan