Search code examples
javascriptember.jspropertiesember-router

I want Ember.js' {{input value="searchTerm"}} to set its value to ' ' when the URL changes


I'll try to simplify this problem as much as possible,

but I need my handlebar.js' {{input value="searchTerm"}} to set the value of searchTerm to 'null' every time the URL changes.

The input described above is meant to auto filter a list on the same page. Typing in the input automatically updates the value of 'searchTerm' to whatever is typed

The value searchTerm is defined in this action named searchResults

This is a property in the controller:

searchResults: function() {
    var searchTerm = this.get('searchTerm');
    var regExp = new RegExp(searchTerm, 'i');

    // We use `this.filter` because the contents of `this` is an array of objects
    var filteredResults = this.filter(function(category) {
        return regExp.test(category.get('categoryName'));
    });      
    return filteredResults;
}.property('@each.categoryName', 'searchTerm'),

So to break down what I need:

  1. Regardless of what the current value of searchTerm is, it needs to be set to ' '.
  2. Setting the value of searchTerm to ' ' only occurs when the page transitions

Solution

  • This can be done on the Route via didTransition or willTransition event handlers. Routes have a reference to their controller (via this.controller), and you could still get it though controllerFor (e.g.: var c = this.controllerFor('controllerName'); so you could do something like this:

    App.SomeRouteThatErasesTheSearchTermRoute = Ember.Route.extend({
      actions: {
        // you could implement with didTransition. No arguments for didTransition tho
        didTransition: function() {
          this.controller.set('searchTerm', '');  
        },
        // OR, implement with willTransition
        willTransition: function(transition) {
          this.controller.set('searchTerm', '');
        }
      }
    });
    

    You could also implement it as a separate method that gets fired on('willTransition'), so you keep any existing handler and just append yours. Then you could make it into a mixin for other routes to use or other routes can inherit from this class without breaking any other custom transition handler, if any.