i have a service to manage all the errors and alerts in my app. and the code looks like this
Service
import Ember from 'ember';
export default Ember.Service.extend({
messages: null,
init() {
this._super(...arguments);
this.set('messages', []);
},
add: function (severity, msg, messageType) {
if (severity === 'error') {severity = 'danger';}
var msgObject ={
severity: severity,
messageType: messageType,
msg: msg,
msgId: new Date()
};
this.get('messages').pushObject(msgObject);
},
remove(msgId) {
this.get('messages').removeObject(msgId);
},
empty() {
this.get('messages').clear();
}
});
Component
import Ember from 'ember';
export default Ember.Component.extend({
messageType:'global',
messageHandler: Ember.inject.service(),
messages: function(){
return this.get('messageHandler.messages').filterBy('messageType',this.get('messageType'));
}.property('messageHandler.messages'),
actions : {
dismissAllAlerts: function(){
this.get('messageHandler').empty();
},
dismissAlert: function(msgId){
this.get('messageHandler').remove(msgId);
}
}
});
Initializer
export function initialize(container, application) {
application.inject('component', 'messageHandler', 'service:message-handler');
}
export default {
name: 'message-handler',
initialize : initialize
};
Template
import Ember from 'ember';
export default Ember.Component.extend({
messageType:'global',
messageHandler: Ember.inject.service(),
messages: function(){
return this.get('messageHandler.messages');
}.property('messageHandler.messages'),
actions : {
dismissAllAlerts: function(){
this.get('messageHandler').empty();
},
dismissAlert: function(msgId){
this.get('messageHandler').remove(msgId);
}
}
});
and whenever there is an error i will add it like this
this.get('messageHandler').add('error',"Unable to get ossoi details","global");
my problem is the filterBy in the component is not working. if i remove the filterBy() it works and i can see the error in the template. am kinda new to ember so if anyone can help me figure out what am missing here or if there is a better way of doing this please let me know
filterBy usage is good and it should be working well. but messages computed property will not be recomputed whenever you add/remove item from messageHandler.messages.
messages: Ember.computed('messageHandler.messages.[]', function() {
return this.get('messageHandler.messages').filterBy('messageType', this.get('messageType'));
}),
In the above code I used messageHandler.messages.[] as dependant key for the messages computed property so that it will be called for add/remove items.
Refer:https://guides.emberjs.com/v2.13.0/object-model/computed-properties-and-aggregate-data/
Computed properties dependent on an array using the [] key will only
update if items are added to or removed from the array, or if the
array property is set to a different array.
Related
I want to access a child route via url eg:https://my-app.com/dashboard/library. When i click this, Ember redirects me to https://my-app.com/dashboard and populates this route's model data correctly, but i want to go to https://my-app.com/dashboard/library, with its new model data.
From the other hand i can access https://my-app.com/login via url, that has no model data btw.
At environment.js i have locationType: "auto", and my router.js is like:
Router.map(function() {
this.route('login');
this.route('dashboard', function() {
this.route('child', {path: '/child/:child_id'});
this.route('library');
});
});
My Routes:
// Route: dashboard
import Ember from 'ember';
import RouteHistoryMixin from 'ember-route-history/mixins/routes/route-history';
export default Ember.Route.extend(RouteHistoryMixin, {
model: function() {
let userId = this.authentication.getPlayerId();
let actions = this.store.findAll('action');
return Ember.RSVP.hash({
actions: actions,
tasks: Ember.RSVP.all([actions]).then((actions) => {
return this.store.findAll('task')
}),
rank: this.store.findAll('rank')
});
},
afterModel: function(){
this.transitionTo('dashboard.index'); // needless
},
setupController(controller, model) {
this._super(...arguments);
Ember.set(controller, 'tasks', model.tasks);
Ember.set(controller, 'rank', model.rank);
}
// . . .
And
// Route: dashboard/library
import Route from '#ember/routing/route';
import Ember from 'ember';
import RouteHistoryMixin from 'ember-route-history/mixins/routes/route-history';
export default Route.extend(RouteHistoryMixin, {
complete: Ember.inject.service(),
queryParams: {
taskId: {}
},
model(params) {
if(params.taskId) {
return Ember.RSVP.hash({
article: this.store.query('article', { filter: '{"inSyllabus": true}'}),
task: this.store.query('task', { filter: '{"id": ' + params.taskId + '}'})
});
}
else {
return Ember.RSVP.hash({
article: this.store.query('article', { filter: '{"inSyllabus": true}'})
});
}
},
setupController(controller) {
this._super(...arguments);
if (controller.taskId)
this.store.findRecord('task', controller.taskId).then((task) => {
controller.set('libraryQueryParam', task.points);
// Notify Task completion
let payload = {
startDate: new Date(),
endDate: new Date(),
points: task.points,
entries: 1
};
// PUT HTTP COMMAND FOR PLAYER
let playerTask = this.store.createRecord('playTaskTest', payload);
playerTask.save();
});
}
// . . .
May be a configuration flag or a Router config issue ?
How can i access this child route via url or has something like that happened to any of you?
I think the issue is in the dashboard. at the afterModel hook:
afterModel: function(){
this.transitionTo('dashboard.index'); // needless
}
This part redirects to dashboard.index every time you call dashboard route. Remember dashboard.index is a child route same as child and library so you will never reach them.
UPDATE:
Can anyone help? I have been pursuing this without luck for the better half of this week. I do notice that the client is generating two POSTs. I have added code for the adapter. Is there anywhere else I should be looking?
I am going through the video tutorial provided below and am unable to resolve two errors when I click the submit button to save data to the database.
No model was found for 'user'
Two POSTs are being generated. This results in an Assertion Failed error, which I suspect is because the ID returned from the server does not match the current ID on the front-end.
I see that the database has two new records. When I click on the submit button again then the application takes me back to the todo-items page where it shows the two records. Can anyone advise what I am doing wrong?
Current versions:
Ember : 3.2.2
Ember Data : 3.2.0
jQuery : 3.3.1
Ember Simple Auth : 1.7.0
Video tutorial (the error occurs at the 11:30 mark): https://www.youtube.com/watch?v=bZ1D_aYGJnU. Note: the author of the video seems to have gotten the duplicate POST issue to go away right at the end of the video, but I do not see how.
Component/forms/todo-item-form/component.js
import Component from '#ember/component';
export default Component.extend({
actions:{
save(){
this.get('submit')();
}
}
});
Component/forms/todo-item-form/template.hbs
<form {{action "save" on="submit"}}>
{{input placeholder="description" value=todoItem.description}}
<br />
{{#if todoItem.validations.isValid}}
<button type="submit">Add</button>
{{else}}
<button type="submit" disabled>Add</button>
{{/if}}
</form>
templates/s/todo-items/add.hbs
{{forms/todo-item-form
todoItem=model
submit=(route-action "submitAction")
}}
{{outlet}}
models/todo-item.js
import DS from 'ember-data';
import { validator, buildValidations } from 'ember-cp-validations';
const { attr, belongsTo } = DS;
const Validations = buildValidations({
description: [
validator('presence', true),
validator('length', {
min: 4
})
]
});
export default DS.Model.extend(Validations, {
description: attr('string'),
owner: belongsTo('person')
});
adapter/Application.js
import DS from 'ember-data';
import ENV from 'todo-list-client/config/environment';
const {computed, inject :{service} } = Ember;
export default DS.JSONAPIAdapter.extend({
session: service(),
namespace: ENV.APP.namespace,
host: ENV.APP.host,
headers: computed('session.data.authenticated.token', function() {
let token = this.get('session.data.authenticated.access_token');
return { Authorization: `Bearer ${token}` };
}),
})
routes/s/todo-items/add.js
import Route from '#ember/routing/route';
export default Route.extend({
model(){
return this.store.createRecord('todo-item');
},
actions: {
submitAction() {
this.get('controller.model')
.save()
.then(() => {
this.transitionTo('s.todo-items');
});
}
},
});
The author adds Ember-Data-Route at about 15m5s for the add.js route as a mixin. This cleans up after the model.
He starts the explanation at that point, adds it in over the next minute or two in the video:
https://youtu.be/bZ1D_aYGJnU?t=15m5s
import Ember from 'ember';
import DataRoute from 'ember-data-route';
export default Ember.Route.extend(DataRoute, {
model() {
return this.store.createRecord('todo-item');
},
actions: {
save() {
this.get('controller.model')
.save()
.then(() => {
this.transitionTo('s.todo-items');
});
}
},
});
I'm trying to use ember-light-table and I'm having some troubles on updating my array of objects.
When I use the action updateList(), I can see both arrays changing (adding/removing objects to the list), but the computed property tableModel is not triggered!
I thought pushObjects() would do the trick, but it's not notifying for some reason (it's adding). I also tried to initialize select_people with Ember.A(), although [] should already be an ember array...
My mixin:
// table-testing
import Ember from 'ember';
import Table from 'ember-light-table';
export default Ember.Mixin.create({
table: null,
tableColumns: null,
tableModel: null,
init() {
this._super(...arguments);
let table = new Table(this.get('tableColumns'), this.get('tableModel'), { enableSync: this.get('enableSync') });
this.set('table', table);
}
});
My controller
import Ember from 'ember';
import TableTesting from '../mixins/table-testing';
const { computed } = Ember;
export default Ember.Controller.extend(TableTesting, {
tableColumns: computed(function() {
return [{
label: 'First Name',
valuePath: 'firstName',
width: '50%',
sortable: false,
}, {
label: 'Last Name'
valuePath: 'lastName',
width: '50%'
}]
}),
tableModel: computed('selected_people.#each.firstName', function() {
// THIS MESSAGE ONLY SHOW WHEN VIEW IS RENDERED
// I've tried .[], .#each, .length... none of them worked and I believe #each.firstName would be the most appropriated from what I've read
console.log('computed method not showing',this.get('selected_people'));
return this.get('selected_people');
}),
init() {
this._super(...arguments);
this.set('selected_people',[]);
},
actions: {
updateList(item, moveToList) {
let removeFromList, fromList, toList;
if (moveToList === 'people') {
removeFromList = 'selected_people'
} else if (moveToList === "selected_people") {
removeFromList = 'people';
}
// get the object lists
fromList = this.get(removeFromList);
toList = this.get(moveToList);
// update list ---> HERE I UPDATE USING KOVL METHOD
toList.pushObjects(item);
fromList.removeObjects(item);
console.log('update!',this.get('selected_people'));
}
}
Just make sure tableModel should be accessed/required by the template or in code.
Computed property is lazy, so it will be calculated when you ask for it either inside the code or in a template. otherwise, it will not be called.
First time when we call, it will return result and it will be cached. and subsequent access will get it from cache. Changing any of the dependent properties causes the cache to invalidate so that the computed function runs again on the next access.
Mostlty copied from guides.emberjs
I'm writing an Ember App with jQuery Datatables. I want to send the action from the controller to refresh the table, I've used Ember Component Inbound Actions. Here is my Code:
import Ember from 'ember';
import InboundActions from 'ember-component-inbound-actions/inbound-actions';
export default Ember.Component.extend(InboundActions,{
init() {
this._super(...arguments);
},
didInsertElement() {
var table = this.$('#example').DataTable({
var _this=this;
})
},
actions: {
check: function() {
this.table.ajax.reload( null, false );
}
},
});
The result is:
Uncaught TypeError: Cannot read property 'ajax' of undefined
How to properly use this action to reload the datatables?
So, I am using bootstrap-tags from https://github.com/maxwells/bootstrap-tags.
I am trying to implement the tags into an Ember component which currently looks like this:
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'input',
classNames: null,
value: null,
initTagsInput() {
const $el = this.$();
const _this = this;
$el.tag({
placeholder: 'enter associated plasmids',
beforeAddingTag: function(tag){ //here is my problem I think?
this.set('value', tag);
}
})
},
didInsertElement() {
this._super();
this.initTagsInput();
}
});
The problem I am having is trying to set the value, but when I check my console or ember debugger, no value is every being assigned (value is null still). It's like the beforeAddingTag never works! I am pretty new to ember so any clarity on wrapping this library will help.
Do I need to use an observable somewhere?
I think you want:
this.set('value', tag);
To be:
_this.set('value', tag);
And
this.$().tag(/**/)
To be:
this.$().tags(/**/)
Also the examples for that library is using a div so we can delete:
tagName: 'input'
The placeholder is added differently in this library too:
placeholder: 'enter associated plasmids'
Should be:
placeholderText: 'enter associated plasmids'
That said we can make this refer to the outer context with fat arrows from ES6 and make it prettier:
import Ember from 'ember';
export default Ember.Component.extend({
classNames: null,
value: null,
initTagsInput() {
this.$().tags({
placeholderText: 'enter associated plasmids',
beforeAddingTag: tag => {
this.set('value', tag);
}
})
},
didInsertElement() {
this._super();
this.initTagsInput();
}
});