Actions in Routes?


#1

Hi.I am new to ember.I’ve been following a tutorial, and something about actions bugged my mind.There is an ‘index’ template.Which doesn’t have a model.Tutorial used a controller for ‘saveInvitation’ action.

{{input type="email" value=emailAddress"}}
<button type="submit" {{action 'saveInvitation' }}></button>
 ---Corresponding contoller code snippet below---
actions: {
saveInvitation() {
  const email = this.get('emailAddress');
  const newInvitation = this.store.createRecord('invitation', { email: email });
  newInvitation.save();}

Then, later on, there is an object, which doesn’t have a controller, and the action goes on rotues file.But this time, ‘model.value’ attribute is passed.

 {{input type="text" value=model.name class="form-control" placeholder="The name of the Library"}}
 <button type="submit" {{action 'saveLibrary' model}}>Add to library list</button>
 ----Corresponding code snippet in ROUTEs file below ----
actions: {

saveLibrary(newLibrary) {
  newLibrary.save().then(() => this.transitionTo('libraries'));
}

It doesn’t make sense to me, why do we add ‘model.’ to objects properties in input fields.Also why the way we define the action has changed.Shouldn’t it be like this:

actions: {
  const property1 = this.get('property1');
  const property2 = this.get('property2');
  and so on...
  const newLibrary=this.store.createRecord('library', {properties: values}).save();}

#2

It looks like the tutorial is doing two different approaches in binding the model to the input helper.

The first example is is binding the emailAddress property directly to the input helper. than creating a record and saving it. Like you said, he isn’t using a model. He is simply creating a record and putting in the Ember Data Store.

The second example, he is directly binding the route’s model to the input helper and then saving it via action. Here it looks like he has a route with a model. and then saves it in saveLibrary(). You don’t have to add model to the input fields you are the developer and you can decide what fields to pull and save into the data store. The goal is to do it in a way that is most maintainable!


#3

Thanks for the answer.But, is there any conventional way of this? I mean with/without model, should actions go in routes file or controller?


#4

Actions that manipulate data should go where that data has been loaded (i.e. to the data owner). This is typically a route. It would make a lot of sense for Ember to incorporate the ember-route-action-helper.


#5

Agreed. I’ve used ember-route-action-helper today and it saves a lot of boilerplate from what I can tell.


#6

Most importantly, it changes data in the data owner.