EmberError: Nothing handled the action - ember.js

I have been struggling with making my Ember Application work with Firebase.
I went through all the posts here on Stackoverflow about the similar matter but I did not find the answer to my problem. So here it is:
Whenever I try to put data into input fields and submit them with a button i get the console error:
EmberError
code : undefined
description : undefined
fileName : undefined
lineNumber : undefined
message :
"Nothing handled the action 'createBook'. If you did handle the action, this error can be caused by returning true from an action handler in a controller, causing the action to bubble."
My model:
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
author: DS.attr('string'),
picture: DS.attr('string'),
buyer: DS.attr('string'),
bought: DS.attr('boolean', { defaultValue: false }),
createdAt: DS.attr('date', { defaultValue() { return new Date(); } })
});
And my Controller:
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
createBook: function(){
var newBook = this.store.createRecord('book', {
title: this.get('title'),
author: this.get('author'),
picture: this.get('picture'),
buyer: this.get('buyer'),
bought: this.set(false),
createdAt: new Date().getTime()
});
newBook.save();
//reset values after create
this.setProperties({'title' : '',
'author' : '',
'picture' : '',
'buyer' : ''
});
}
}
});
The template:
{{outlet}}
<div style ="margin-left:130px;">
<h1> blabla </h1>
{{input type="text" value=title placeholder="Add Title"}}<br>
{{input type="text" value=author placeholder="Add author"}}<br>
{{input type="text" value=picture placeholder="Add picture"}}<br>
{{input type="text" value=buyer placeholder="buyer"}}<br>
</div>
<button class="btn btn-default" {{action "createBook" }}> Create</button>
{{#each model as |book|}}
<ul>
<li>{{book.title}}</li>
</ul>
{{/each}}
The connection between the Firebase and Ember is set up 100 % properly.
For now the rules on firebase have been set to true for both read and write.
The only problem is that it does not post the data to Firebase.

Thanks #Lux for your advice.
There were several things wrong with my code.
I created model and controller called book, but route called books.
I did not know that it will have an effect on my model and controller.
So i ended up with:
app/controllers/book.js
app/model/book.js
app/routes/book.js
app/templates/book.hbs
This was not enough. I also had to edit content of my controller
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
createBook: function(){
var newBook = this.store.createRecord('book', {
title: this.get('title'),
author: this.get('author'),
picture: this.get('picture'),
buyer: this.get('buyer')
});
newBook.save();
//reset values after create
this.setProperties({'title' : '',
'author' : '',
'picture' : '',
'buyer' : ''
});
}
}
});
As you can see I have removed the lines that were setting the default values of bought and createdAt. It was enough just to set them inside the model itself.

Related

ember firebase pass models to action handler

I have ember data models hooked with firebase, characters and spells. I can create new models and save them to firebase. Now I wanted to add spells to character. I defined that character has many spells:
export default DS.Model.extend({
chClass: DS.attr(),
chName: DS.attr(),
chImage: DS.attr(),
chSpells: DS.hasMany('spell', {async: true}),
});
In my hbs I listed spells in <select> element, there is also input fields and add button.
Add new character <br>
name {{input value=mchName }}<br>
class {{input value=mchClass }}<br>
image {{input value=mchImage }}<br>
<br>
Choose Spells:<br>
<select name="spellslist" multiple>
{{#each spells as |spell index|}}
<option value="{{index}}">{{spell.spName}}</option>
{{/each}}
</select>
<button {{action 'addChar' spells}}>add</button><br>
So when user types in character name, level and picks some spells I want to call addChar action function on add button and pass this data.
export default Ember.Controller.extend({
mchName:'',
mchClass:'',
mchImage:'',
store: Ember.inject.service(),
actions: {
addChar: function(spells) {
var newChar = this.store.createRecord('character');
newChar.set("chName", this.mchName);
newChar.set("chClass", this.mchClass);
newChar.set("chImage", this.mchImage);
newChar.get("chSpells").addObject(?????? how to get spell here ?????);
newChar.save();
I know how to pass string from inputs, but I dont know how to pass selected spells to this function, its killing me.
I'm assuming that you (as admin) are going to populate the spells table. Now ... assuming that a character can have many spells and a spell can have many characters, here's how one can approach this (note that I'm using a controller ... you should ideally be doing this in a component):
Character model is simplified:
//app/models/character.js
import DS from 'ember-data';
export default DS.Model.extend({
chName: DS.attr(),
chSpells: DS.hasMany('spell', {async: true})
});
Spells model is also simplified for this example:
//app/models/spell.js
import DS from 'ember-data';
export default DS.Model.extend({
spName: DS.attr(),
spellChar: DS.hasMany('character', {async: true})
});
We need an include helper for the multiline select. Review this article for details:
//app/helpers/include.js
import Ember from 'ember';
export function include(params/*, hash*/) {
const [items, value] = params;
return items.indexOf(value) > -1;
}
export default Ember.Helper.helper(include);
Here's the application route:
app/routes/application.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function(){
var spells = this.store.findAll('spell');
return spells;
}
});
And the application controller:
//app/controllers/application.js
import Ember from 'ember';
export default Ember.Controller.extend({
selectedSpellIds: [],
actions: {
selectSpell(event){
const selectedSpellIds = Ember.$(event.target).val();
this.set('selectedSpellIds', selectedSpellIds || []);
},
addChar: function(){
var charName = this.get('mchName');
var _this = this;
var spells = this.get('selectedSpellIds');
var spellObjArray = spells.map(function(spellId){
return _this.store.peekRecord('spell', spellId );
});
var charToSave = this.store.createRecord('character', {
chName: charName,
chSpells: spellObjArray
});
charToSave.save();
},
}
});
And the application template:
//app/templates/application.hbs
Add new character <br>
name {{input value=mchName }}<br>
<br>
Choose Spells:<br>
<select multiple onchange={{action "selectSpell"}}>
{{#each model as |spell|}}
<option value={{spell.id}} selected={{include selectedSpellIds spell.id}}>{{spell.spName}}</option>
{{/each}}
</select>
<button {{action 'addChar'}}>add</button><br>

Use ember-simple-validaiton to validate property on hasMany relation

this question is about particular plugin - ember-cli-simple-validation.
Lets assume that there is two models
User = DS.Model.extend({
name: DS.attr()
emails: DS.hasMany('email')
})
Email = DS.Model.extend({
address: DS.attr()
emails: DS.belongsTo('user')
})
and user dynamically create emails:
<button {{action 'createEmail'}}>Add Email</button>
{{#each model.emails as |email index|}}
{{input value=email.address}}
{{/each}}
is it possible to use ember-simple-validaiton in this situation to validate presence of address on each of the emails?
I tried to go with validateEach but getting an Error while processing route: profile self.get(...).forEach is not a function TypeError: self.get(...).forEach is not a function error on the https://github.com/toranb/ember-cli-simple-validation/blob/master/addon/mixins/validate.js#L66
controller:
import Ember from 'ember';
import {ValidationMixin, validateEach} from "ember-cli-simple-validation/mixins/validate";
var isLegit = function(address) {
return address && address.length > 3;
};
export default Ember.Controller.extend(ValidationMixin, {
emailAddressValidation: validateEach("model.emails", isLegit),
actions: {
createChildren: function(type) {
this.store.createRecord(type, {profile: this.get('model')});
},
});
template:
{{#each model.emails as |email index|}}
{{input value=email.address}}
{{#validation-error-field submitted=submitted field="address" model=mode.emails index=index validation="basic"}}invalid address{{/validation-error-field}}
{{/each}}
model:
import Ember from 'ember';
import DS from 'ember-data';
export default DS.Model.extend{
address: DS.attr(''),
kind: DS.attr(''),
contactable: DS.belongsTo('contactable', { polymorphic: true, inverse: 'emails', async: false }),
kindIsPrimed: false,
kindChanged: Ember.observer('kind', function () {
this.set('kindIsPrimed', true);
}),
addressIsPrimed: false,
addressChanged: Ember.observer('address', function () {
this.set('addressIsPrimed', true);
})
});
On the surface (without running the code) you might alter your hbs from this
{{#each model.emails as |email index|}}
{{input value=email.address}}
{{#validation-error-field submitted=submitted field="address" model=mode.emails index=index validation="basic"}}invalid address{{/validation-error-field}}
{{/each}}
to instead ...
{{#each model.emails as |email index|}}
{{input value=email.address}}
{{#validation-error-field submitted=submitted field="address" model=email index=index validation="basic"}}invalid address{{/validation-error-field}}
{{/each}}
In the validateEach scenario (for array validation) you need to set the model and index on each iteration. The model should still be the individual model (not the array itself).
Another example that's tested in the addon for reference
https://github.com/toranb/ember-cli-simple-validation/blob/master/tests/dummy/app/templates/many.hbs

ember-data stores a string instead of a number

In my ember app I want to reuse a model attribute as soon as the form is submitted. But the store seems to keep it as string unless I reload the whole route. I am using this and the following components:
Ember : 1.12.0
Ember Data : 1.0.0-beta.18
jQuery : 1.11.3
/app/models/purchase.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
amount: DS.attr('number'),
createdAt: DS.attr('date', {
defaultValue: function() { return new Date(); }
}),
.. other callback and associations..
});
/app/controllers/ledger/purchases/new.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function () {
return {
newPurchase: this.store.createRecord('purchase', {
name: null,
amount: null,
player: null
})
}
}
});
/app/templates/ledger/purchases/new.hbs
<div class="row">
<div class="col-xs-12">
<h4>New purchase</h4>
<form>
<div class="form-group">
<label for="name" class="sr-only control-label">name</label>
{{input id='name' type="text" value=newPurchase.name placeholder="What" class="form-control"}}
</div>
<div class="form-group">
<label for="amount" class="sr-only control-label">amount</label>
{{input id='amount' type='number' value=newPurchase.amount placeholder="How much" class="form-control"}}
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" {{action "create"}}>create</button>
{{#link-to 'ledger.purchases' tagName="button" class="btn btn-link" }}cancel{{/link-to}}
</div>
</form>
</div>
</div>
/app/controllers/ledger/purchases/new.js
import Ember from 'ember';
export default Ember.Controller.extend({
newPurchase: Ember.computed.alias('model.newPurchase'),
actions: {
create: function() {
var np = this.get('newPurchase');
console.log(Ember.typeOf(np.get('amount')));
........
save np etc...
}
}
});
the console log call clearly shows that the type is a string. The ember inspector shows the same. However data are correctly saved to the backend because after reloading everything is fine. But I need the amount as a number as soon as it is submitted because I use it to make and show the sum of all purchases.
Okay, I think I know what's going on. Setting input type to number won't help here. Value is still recognized as string. Usually when you submit form, backend anyway returns this value formatted as a number and problem's gone. You can see this even when you mock your data with a number, without a backend.
My solution would be to use a computed property for input component. Model:
export default DS.Model.extend({
name: DS.attr('string'),
amount: DS.attr('number'),
createdAt: DS.attr('date', {
defaultValue: function() { return new Date(); }
}),
amountAsNum: Ember.computed('amount', {
get: function () {
return parseFloat(this.get('amount'));
},
set: function (key, value) {
var valueToSet = parseFloat(value);
this.set('amount', valueToSet);
return valueToSet;
}
}),
.. other callback and associations..
});
Template:
{{input id='amount' type='number' value=newPurchase.amountAsNum placeholder="How much" class="form-control"}}
Now, you can check typeof(amount) before save and it'll give you number. Demo on JS Bin.

EmberJS computed sort property conflicting with jQuery UI Sortable

I am having an issue with getting drag-and-drop sort functionality with EmberJS working.
The tutorials that cover this issue don't provide any help on the initial sort, which I am doing through a computed property.
What I'm encountering seems to be a race condition between ember's rerender when the sortedItems computed property changes and jQueryUI Sortable updating the DOM. List Items get duplicated, or disappear altogether upon sorting.
Route
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return Ember.Object.create({
id: 1,
title: "Title",
subtitle: "Subtitle",
items: [
Ember.Object.create({
name: "Item 2",
sortOrder: 2,
id: 1
}),
Ember.Object.create({
name: "Item 1",
sortOrder: 1,
id: 2
}),
Ember.Object.create({
name: "Item 3",
sortOrder: 3,
id: 3
})
]
});
}
});
Controller
import Ember from 'ember';
export default Ember.ObjectController.extend({
sortProperties: [ 'sortOrder' ],
sortedItems: Ember.computed.sort('model.items', 'sortProperties'),
actions: {
updateSortOrder: function(indexes) {
this.get('items').forEach(function(item) {
var index = indexes[item.get('id')];
item.set('sortOrder', index);
});
}
}
});
View
import Ember from 'ember';
export default Ember.View.extend({
didInsertElement: function() {
var controller = this.get('controller');
this.$(".item-list").sortable({
update: function(event, ui) {
var indexes = {};
$(this).find('li').each(function(index) {
indexes[$(this).data('id')] = index;
});
controller.send('updateSortOrder', indexes);
}
})
}
});
Template
<h1>{{ title }}</h1>
<h2>{{ subtitle }}</h2>
<ul class="item-list">
{{#each item in sortedItems }}
<li data-id="{{ unbound item.id }}">
name: {{ item.name }}<br />
sortOrder: {{ item.sortOrder }}<br />
id: {{ item.id }}
</li>
{{/each}}
</ul>
Here's a Barebones Ember app that reproduces the issue: https://github.com/silasjmatson/test-sortable
Question
Is there a way to avoid this race condition or sort only once when the controller is initialized?
Apologies if there is already an answer on the interwebs for this. I haven't been able to resolve this despite a week of searching/experimenting.
You can sort only once when the controller is initialised:
sortedItems: Ember.computed(function() {
return Ember.get(this, 'model.items').sortBy('sortOrder');
})
Because you're using the computed sort property it is attempting to sort the list for you whenever the sortOrder property changes on any item, which is rerendering the #each and doing something funky.
Just sort once initially using the method above and then let jQuery handle the order of items - rather than jQuery and Ember.

Weird binding with Ember.Select value

I'm having a weird issue with the Ember.Select view when I try to bind its value to a model.
Here is an abstract of what I'm doing, the complete jsbin can be found here:
Using JavaScript: http://jsbin.com/jayutuzazi/1/edit?html,js,output
Using CoffeeScript: http://jsbin.com/nutoxiravi/2/edit?html,js,output
Basically what I'm trying to do is use an attribute of a model to set an attribute of another model.
I have the Age model like this
App.Age = DS.Model.extend({
label: DS.attr('string'),
base: DS.attr('number')
});
And an other model named Person like this
App.Person = DS.Model.extend({
name: DS.attr('string'),
ageBase: DS.attr('number')
});
The template looks like this:
<!-- person/edit.hbs -->
<form>
<p>Name {{input value=model.name}}</p>
<p>
Age
{{view "select" value=model.ageBase
content=ages
optionValuePath="content.base"
optionLabelPath="content.label"}}
</p>
</form>
What I am trying to do is have a select in the Person edit form that lists the ages using base as value and label as label.
I expect the correct value to be selected when loading and to change when the selected option changes.
Has can be seen in the jsbin output, the selected is correctly populated but it sets the ageBase value of the edited person to undefined and does not select any option. The model value is correctly set when an option is selected though.
Am I doing something wrong ? Is it a bug ? What am I supposed to do to make this work ?
Thank you :)
You can conditionally render based on fulfilment of the ages as follows, since select doesn't handle promises (more on that below):
{{#if ages.isFulfilled}}
{{view "select" value=ageBase
content=ages
optionValuePath="content.base"
optionLabelPath="content.label"}}
{{/if}}
I updated your JsBin demonstrating it working.
I also illustrate in the JsBin how you don't have to qualify with model. in your templates since object controllers are proxies to the models they decorate. This means your view doesn't have to be concerned with if a property comes from the model or some computed property on the controller.
There is currently a PR #9468 for select views which I made a case for getting merged into Ember which addresses some issues with selection and option paths. There is also meta issue #5259 to deal with a number of select view issues including working with promises.
From issue #5259 you will find that Ember core developer, Robert Jackson, has some candidate select replacements. I cloned one into this JsBin running against latest production release version of Ember.
There is nothing at all preventing you using Roberts code as a select view replacement in your app. Asynchronous collections/promises will just work (and it is MUCH faster rendering from the benchmarks I have seen).
The template for that component is just:
{{#if prompt}}
<option disabled>{{prompt}}</option>
{{/if}}
{{#each option in resolvedOptions}}
<option {{bind-attr value=option.id}}>{{option.name}}</option>
{{/each}}
The js of the component is:
App.AsyncSelectComponent = Ember.Component.extend({
tagName: 'select',
prompt: null,
options: null,
initialValue: null,
resolvedOptions: null,
resolvedInitialValue: null,
init: function() {
var component = this;
this._super.apply(this, arguments);
Ember.RSVP.hash({
resolvedOptions: this.options,
resolvedInitialValue: this.initialValue
})
.then(function(resolvedHash){
Ember.setProperties(component, resolvedHash);
//Run after render to ensure the <option>s have rendered
Ember.run.schedule('afterRender', function() {
component.updateSelection();
});
});
},
updateSelection: function() {
var initialValue = Ember.get(this, 'resolvedInitialValue');
var options = Ember.get(this, 'resolvedOptions') || [];
var initialValueIndex = options.indexOf(initialValue);
var prompt = Ember.get(this, 'prompt');
this.$('option').prop('selected', false);
if (initialValueIndex > -1) {
this.$('option:eq(' + initialValueIndex + ')').prop('selected', true);
} else if (prompt) {
this.$('option:eq(0)').prop('selected', true);
}
},
change: function() {
this._changeSelection();
},
_changeSelection: function() {
var value = this._selectedValue();
this.sendAction('on-change', value);
},
_selectedValue: function() {
var offset = 0;
var selectedIndex = this.$()[0].selectedIndex;
if (this.prompt) { offset = 1; }
return Ember.get(this, 'resolvedOptions')[selectedIndex - offset];
}
});
The problem is that in:
{{view "select" value=model.ageBase
When the app starts, value is undefined and model.ageBase gets synchronized to that before value is synchronized to model.ageBase. So, the workaround is to skip that initial undefined value.
See: http://jsbin.com/rimuku/1/edit?html,js,console,output
The relevant parts are:
template
{{view "select" value=selectValue }}
controller
App.IndexController = Ember.Controller.extend({
updateModel: function() {
var value = this.get('selectValue');
var person = this.get('model');
if ( value ) { // skip initial undefined value
person.set('ageBase', value);
}
}.observes('selectValue'),
selectValue: function() {
// randomly used this one
return this.store.find('age', 3);
}.property()
});
givanse's answer should work.
I don't think it's because value is undefined, but because value is just an integer (42) and not equal to any of the selects content, which are Person objects ({ id: 2, label: 'middle', base: 42 }).
You could do something similar to what givens suggests or use relationships.
Models
//
// Models
//
App.Person = DS.Model.extend({
name: DS.attr('string'),
ageBase: DS.belongsTo('age', { async: true })
});
App.Age = DS.Model.extend({
label: DS.attr('string'),
base: DS.attr('number')
});
//
// Fixtures
//
App.Person.reopenClass({
FIXTURES: [
{ id: 1, name: 'John Doe', ageBase: 2 }
]
});
App.Age.reopenClass({
FIXTURES: [
{ id: 1, label: 'young', base: 2 },
{ id: 2, label: 'middle', base: 42 },
{ id: 3, label: 'old', base: 82 }
]
});
Template:
<h1>Edit</h1>
<pre>
name: {{model.name}}
age: {{model.ageBase.base}}
</pre>
<form>
<p>Name {{input value=model.name}}</p>
<p>
Age
{{view "select" value=model.ageBase
content=ages
optionValuePath="content"
optionLabelPath="content.label"}}
</p>
</form>
Ok, I found a solution that I think is more satisfying. As I thought the issue was coming from ages being a promise. The solution was to ensure that the ages list was loaded before the page was rendered.
Here is how I did it:
App.IndexRoute = Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
person: this.store.find('person', 1),
ages: this.store.findAll('age')
});
}
});
That's it! All I need from there is to change the view according the new model:
{{#with model}}
<form>
<p>Name {{input value=person.name}}</p>
<p>
Age
{{view "select" value=person.ageBase
content=ages
optionValuePath="content.base"
optionLabelPath="content.label"}}
</p>
</form>
{{/with}}
The complete working solution can be found here: http://jsbin.com/qeriyohacu/1/edit?html,js,output
Thanks again to #givanse and #Larsaronen for your answers :)