Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus after initialization with emberjs?

Tags:

ember.js

I'm new to Ember.js. I want to focus on TextField(in sample, id="text") after initialization, but in ready function, doesn't work focus method...

<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>
like image 640
arumons Avatar asked Feb 27 '12 16:02

arumons


2 Answers

The following code does work:

<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>
like image 76
Mike Aski Avatar answered Nov 09 '22 09:11

Mike Aski


Subclassing TextField and then spreading a custom View around your templates seemed a bit messy to me, so I wrote this little 1kb package that lets you do this 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 }} {# <<<<-- Magic happens here #}
  </script>
  <!-- your app -->
  <script>
    Ember.Application.create();
  </script>
</body>

You can get it from https://github.com/AndreasPizsa/ember-autofocus or with bower install ember-autofocus. I appreciate feedback!

like image 37
AndreasPizsa Avatar answered Nov 09 '22 07:11

AndreasPizsa