How to trigger an action when an input gets focus?

I want to know how to trigger an action when an input gets focused…
right now I’m using this on my template: {{view "clickinput" class="form-control" placeholder="search..." value=s action="focus"}}
and this as the view:

export default Ember.TextField.extend({
  onEvent: 'focusIn',
  focusIn: function() {
    this.sendAction('focusIn', this, event);
  }
});

and this on my controller:

actions: {
  focus: function() {
    alert('f');
  }
}

but it doesn’t work… I get the error: Uncaught Error: Assertion Failed: The focusIn action was triggered on the component <appkit@view:clickinput::ember438>, but the action name (function superWrapper() { var ret, sup = this.__nextSuper; this.__nextSuper = superFunc; ret = func.apply(this, arguments); this.__nextSuper = sup; return ret; }) was not a string.

why?

The first argument to sendAction is actually the name of the property that contains the name of the action that you want to send. This means you need to specify it on your input (which uses TextField internally).

{{input focusIn=focused}}

in your controller

 actions: {
  focused: function() {
    alert('f');
  }
}

this is probably the most flexible way to do it. An alternative though is to use triggerAction instead. This allows you to specify the name of the action directly.

export default Ember.TextField.extend({
  onEvent: 'focusIn',
  focusIn: function() {
    this.triggerAction({
      action: 'focusIn',
      target: this.get('controller'),
      actionContext: this.get('context'),
    });
  }
});

For reference here’s the final solution, which is actually really simple! http://emberjs.jsbin.com/rugomufi/3/edit

1 Like