"Global" action with a search field used in various places?


#1

One thing I can’t seem to get my head around is how to use an action associated with a search field that can appear in different places in the app. Right now I’m literally using a form field and a submit button, but that’s re-loading the app on submit.

What is the best practice for this? Is there a “global” action I can use for the app so that a search action can be run from a component or template anywhere in the app? If so, do I have to pass down the reference to the action to every single nested component that will need it?


#2

I would recommend creating the search field as a component that has a two-way binding to the data.

template.hbs {{search-field searchResults=myData}}

search-field.hbs {{input type='text' value=searchVal}} <button {{action 'search'}}>Search</button>

search-field.js

import Ember from 'ember';

export default Ember.Component.extend({
  store: Ember.inject.service(),
  actions: {
    search() {
      var _this = this;
      this.get('store').query('modelToSearch', { fieldToSearch: this.get('searchVal') }).then((data) => {
        _this.set('searchResults', data);
      });
    }
  }
});

#3

that seems quite sensible. Thanks!