set focus in an ember application

2019-05-18 17:53发布

问题:

I want to be able to set the focus to a textarea as a result of a mouse click not in that task area.

As a minimal example, let's say that I'm starting with a text and if you click on it, it gets replaced with a textfield. I can achieve this by a handlebars script:

<script type="text/x-handlebars">
  {{#if isActive}}
  {{view Ember.TextField}}
  {{else}}
  <p {{action foo}}> Click Here to Enter text  </p>
  {{/if}}
</script>

with a controller of

App.ApplicationController = Ember.Controller.extend({
    isActive: false,
    foo: function(){
       this.set("isActive", true);
    }
});

This works to create the textfield on the click, but does not give focus to that text area (it takes a second click to be able to actually enter text).

Is there a good way to achieve this end? I could do something hacky by setting an ID in the template and selecting it with jquery, but that seems inelegant.

回答1:

Consider extending Ember.TextField as follows:

App.FocusedTextField = Em.TextField.extend({
  didInsertElement: function() {
    this.$().focus();
  }
});

Then change you handlebars template to use it instead:

<script type="text/x-handlebars">
  {{#if isActive}}
    {{view App.FocusedTextField}}
  {{else}}
    <p {{action foo}}> Click Here to Enter text  </p>
  {{/if}}
</script>


回答2:

Furthermore, to reduce the didInsertElement and this.$().focus(); which can seem as though you're mixing jQuery into your Ember modules -- and something I hate doing, you can use the Ember.JS way of specifying additional attributes for the Ember.TextField.

We can specify that we're interested in the HTML5 autofocus attribute:

Ember.TextSupport.reopen({
  attributeBindings: ["autofocus"]
});

We can then place the standard Ember.TextField onto our page without having to create another view to extend Ember.TextField:

{{view Ember.TextField autofocus="autofocus"}}

See JSFiddle: http://jsfiddle.net/MdzhN/