How to use autofocus with ember.js templates?

2020-08-20 12:46发布

问题:

I have a simple ember.js text field and I'm trying to add autofocus

{{view PersonApp.SearchField placeholder="search..." valueBinding="searchText"}}

PersonApp.SearchField = Ember.TextField.extend({

});

Can I add this in the javascript or is at as simple as a attribute in the template itself?

回答1:

Update:

More recent versions of Ember now have support for this built in, so you no longer need to reopen TextField to add an attributeBinding. As of January 2014 (commit fdfe8495), you can simply use the HTML5 autofocus attribute in your template:

{{input value=search type="text" placeholder="Search" autofocus="autofocus"}}

Here is a simple jsfiddle demonstration.


Previous Solution:

You can also reopen TextField to allow you to bind the autofocus attribute:

Ember.TextField.reopen({
  attributeBindings: ['autofocus']
}); 

And then in your template:

{{input value=search type="text" placeholder="Search" autofocus="autofocus"}}


回答2:

There is also the option to use the HTML5 autofocus attribute on the TextField.

PersonApp.SearchField = Ember.TextField.extend({
    attributeBindings: ['autofocus'],
    autofocus: 'autofocus'
});

See also documentation on Mozilla Developer Network for further information about the autofocus field:



回答3:

Autofocus meaning that we start focusing on the text box right away? You want didInsertElement for that.

didInsertElement: function() {
    this.$().focus();             
}

http://jsfiddle.net/qKXJt/139/



回答4:

I wrapped this method in a little 1kb package to solve this even a bit more elegantly, directly in the template, without any further coding:

<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 }}
  </script>
  <!-- your app -->
  <script>
    Ember.Application.create();
  </script>
</body>

The package is at https://github.com/AndreasPizsa/ember-autofocus (or on bower install ember-autofocus). Enjoy!