set focus in an ember application

独自空忆成欢 提交于 2019-12-07 23:23: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/



来源:https://stackoverflow.com/questions/14763318/set-focus-in-an-ember-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!