set focus in an ember application

廉价感情. 提交于 2019-12-06 05:03:42

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>

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/

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