How to do an action and redirect using query parameters


#1

I am working on a habit tracking app. I start off with a list of habits. When a user clicks a habit, I want to creates a new event for that habit. I have the habits list working, but I am having difficulty with the creation of the new event.

To create a new event, I have this route:

App.Router.map( function() {
  ⋮
  this.resource( 'new_event', { path: '/event/new/:habit_id' } )
} )

Then the associated router is:

App.NewEventRoute = Ember.Route.extend( {
  model: function(params) {
    return this.store.find( 'habit', params.habit_id )
  },
  setupController: function( controller, model ) {
    controller.set( 'selectedHabit', model )
  }
} )

To the best of my knowledge, the only place I can access the query params is within the model function.

The controller, then, is:

App.NewEventController = Ember.ObjectController.extend( {
  init: function() {
    console.log( 'init', this.get( 'selectedHabit' ) )
    // Logic for adding a new event for the habit
    this.transitionToRoute( 'events' )
  },
  selectedHabit: null,
  ⋮

The returned value for selectedHabit in the controller init is null.


#2

I feel like what you want is an action to create an event with a specified habit instead of a route.

<button {{action 'createEvent' habbitId}}>create event</button>

and on your route you could define the action

App.IndexRoute = Ember.Route.extend({
  actions: {
    createEvent: function (habitId) {
      var self = this;
      var event = this.store.createRecord('event', {habitId: habitId});
      event.save().then(function() {
        // do whatever you want on success
      });
    }
  }
});

#3

That was what I needed. Thanks. Here it is in action.