nick
nick

Reputation: 33

Invoking Ember.js controller function by automating action

Currently my site includes a search bar in my index.ejs file that uses {{action createSearch}} to call my controller's "createSearch" function when a user presses enter or clicks my search button. This works perfectly! Now I am testing out new functionality and want to call my newSearch function directly from my index.ejs file without any user interaction. I've tried using jquery on load to simulate the key press / click but the controller but that doesn't seem to invoke the action event.

edit: functional index.js code included

         {{view Ember.TextField id="new-search" placeholder="enter a few keywords"
             valueBinding="newSearch" action="createSearch"}}         
        <div id="gobutton" {{action createSearch}}><div id="gobutton_inner">SEARCH</div></div>

Upvotes: 3

Views: 1403

Answers (1)

Darshan Sawardekar
Darshan Sawardekar

Reputation: 5075

For system-level actions like this you are better off using events on the ApplicationRoute. Your controllers/views can send an event like createSearch that the route handles typically via the controller that knows how to do this.

App.ApplicationRoute = Em.Route.extend({
  events: {
    createSearch: function(query) {
      var controller = this.controllerFor('search');
      controller.doSearch(query);
    }
  }
});

From any controller's action handler you can trigger the event with,

this.send('createSearch', query);

Or from a view,

this.get('controller').send('createSearch', query);

You will need to wire your individual action handlers to do this event triggering.

Upvotes: 3

Related Questions