2
votes

Ember 1.0.0 RC3 provides a Handlebars helper named {{input}}. Instead of merely updating a String property in the underlying controller, I would like to additionally call a method on the underlying controller whenever the input has changed.

Is there a way to call a controller method after changes to an {{input}} textfield?

1

1 Answers

3
votes

Use the .observes("propertyChangedByInputHelper") on the controller method that shall react on changes.

<--Handlebars template -->
    <script type="text/x-handlebars" id="autocomplete">
        {{input type="text" value=searchText placeholder="Search users..."}}
        <table>
            {{#each searchResults}}
                <tr><td>
                {{#linkTo "user" this}}
                    {{firstName}} {{lastName}}
                {{/linkTo}}
                </td></tr>
            {{/each}}
        </table>
    </script>

.

//inside Ember application / app.js
App.AutocompleteController = Ember.ObjectController.extend({
    searchText: null,         // mutated by "autocomplete" Handlebars template
    searchResults: Ember.A(), //initialize to empty array

    searchForUsers: function() {
        this.set("searchResults", Ember.A() ); // clear possibly non-empty array
        var searchResultsBuilder = Ember.A();
        //...
        //... making modifications to searchResultsBuilder
        //...
        this.get("searchResults").addObjects(searchResultsBuilder);
    }.observes("searchText")
});

N.B.: When searchText changes, a .property("searchText") wouldn't be enough to trigger the searchForUsers method: .property(..) makes the method act only lazily on demand, while .observes(..) makes the method act eagerly.