bcmcfc
bcmcfc

Reputation: 26805

How to show an element when another element is focused in Ember/Handlebars

I have something like this in a Handlebars template:

<input>
<button>save</button>

It'd be very straightforward to achieve the desired effect in jQuery, and in Angular the ng-show directive would probably do the job.

What would be the Ember way of showing the button when input has focus?

At the moment I am playing around with #unless on the assumption that a computed property would do the trick, similar to computeds in Knockout.

App.DashboardView = App.BaseView.extend({
    notesFocused: function () {
        this.$('#notes').is(':focus');
    }
});

and:

{{#unless notesFocused}}
    <button>save</button>
{{/unless}}

This isn't working yet but I suspect I am on the right track. I would appreciate any pointers.

Upvotes: 1

Views: 732

Answers (1)

Marcio Junior
Marcio Junior

Reputation: 19128

You can dispath the focusIn and focusOut events to the controller or route, using focus-in and focus-out from Ember.TextField. And keep the state in a variable:

{{input type="text" focus-in="notesFocusIn" focus-out="notesFocusOut"}}    
{{#unless notesFocused}}
    <button>save</button>
{{/unless}}

controller

App.DashboardController = Ember.Controller.extend({
    notesFocused: false,
    actions: {
        notesFocusIn: function() {
            this.set('notesFocused', true);
        },
        notesFocusOut: function() {
            this.set('notesFocused', false);
        }
    }
});

See this in action http://jsfiddle.net/marciojunior/KN4dk/

Upvotes: 3

Related Questions