2
votes

I have an ember app with a contacts page. I have a list of users which I want to filter according to a) a search query and b) filters saved on the session.currentUser model (using ember-simple-auth-devise).

My route:

import Ember from 'ember';
import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin).extend({
model: function() {
    return this.store.find('user');
},

setupController: function(controller, model){
  this._super(controller, model);

  var currentUser = this.store.fetch('user', this.get('session').get('user_id'));
  // console.log(currentUser);
  controller.set('currentUser', currentUser);
}
});

My controller:

import Ember from 'ember';

export default Ember.ArrayController.extend({

searchText: '',

filterUsers : function() {
    // Function to set the filteredUsers property, set in the route, based on the searchText

    var searchText = this.get('searchText'), regex = new RegExp(searchText, 'i');


    var us = this.get('model').filter(function(item) {

        // Run some filters here...

    });

    this.set('filteredUsers', us);
    return false;
}.observes('searchText', 'model'),

actions: {
    // Click the "Filter" button and update the server
    setFilters: function(){
        this.get('session').get('currentUser').save();
    }
}
});

This works up to a point - entering text in the searchText field runs my filters. However I have two issues that I can't resolve:

  1. How to I make the filterUsers function run when the template first loads, to use variables set on the currentUser model?
  2. How do I make filterUsers run when I call the setFilters method and change the current user?

Many thanks

2

2 Answers

2
votes

To run a method on controller load, run it under the init hook.

export default Ember.ArrayController.extend({
    ...
    filterUsers : function() {
      ...
    }.observes('searchText', 'model').on('init') // <---
    ...
 });

or you can also do:

export default Ember.ArrayController.extend({
    init: function() {
       this._super();
       this.filterUsers();
    }
    ...
 });

To invoke a controller method inside an action, simply call it:

...
actions: {
    setFilters: function(){
        this.filterUsers(); // <--- 
        ...
    }
}
...
0
votes

Maybe I see it too trivial, but to me it looks like you just have to add currentUser to the 'observes' list. When the currentUser is changed, the filterUser method is called automatically, for both your questions.