Ember.js Computed Properties (Overwriting get and set) - javascript

I am working on an Ember.js application and I'm using ember-cli 2.7.
I'm trying to overwrite the properties for get and set, but when I do, I get an unexpected token error.
Here is the code of my controller file:
import Ember from 'ember';
export default Ember.Controller.extend({
isDisabled: true,
emailAddress: '',
actualEmailAddress: Ember.computed('emailAddress', function(){
get(key){
return `getting email...${this.get('emailAddress')}`;
}
}),
emailAddressChanged: Ember.observer('emailAddress', function(){
console.log('observer is called: ', this.get('emailAddress'));
})
});
This seems like a simple solution, but I do not find the bug and it's killing me. Please help me and thank you.

It's a syntax error. function shouldn't be at there. Computed property definition should be like this:
actualEmailAddress: Ember.computed('emailAddress', {
get(key){
return `getting email...${this.get('emailAddress')}`;
},
set(key, value){
//...
}
}),
If you only have a get operation at a computed property, then you can write it as following:
actualEmailAddress: Ember.computed('emailAddress', function(){
return `getting email...${this.get('emailAddress')}`;
}),

Related

Ember.js Observer

I want to use observer on a variable which is in service, that's my code:
const get = Ember.get;
uploader:Ember.inject.service('uploader'),
progressChanged: Ember.observer(this.get('uploader').get('progress'), function() {
console.log('observer is called', this.get('uploader').get('progress'));
}),
That's the error:
Error while processing route: index this.get is not a function
When I'm trying to show the progress in alert:
actions:
{
getProgress()
{
alert("progress:"+this.get('uploader').get('progress'));
}
}
Everything works, but not in an observer. What should I do?
this context is not valid one. Like Kitler suggested, The below should solve your problem.
import Ember from 'ember';
export default Ember.Component.extend({
uploader:Ember.inject.service(),//if service name is uploader
progressChanged: Ember.observer('uploader.progress',function() {
console.log('observer is called', this.get('uploader').get('progress'));
}),
});
I would suggest not to overuse observer, you can try using computed property. If you just want to show progress alone then you dont need observer, you can simply use this.get('uploader.progress') or through Ember.computed.alias('uploader.progress').
Reference: https://guides.emberjs.com/v2.7.0/object-model/observers/

Ember 2.0 router does not load model data?

I have in my router.js:
Router.map(function() {
this.route('portfolio', function() {
this.route('company', { path:'/company/:id' });
});
}
And in my routes/portfolio/company.js:
import Ember from 'ember';
export default Ember.Route.extend({
model: function(params) {
var companyId = params.id;
return new Ember.RSVP.hash({
company: Ember.$.ajax({ url: '/api/company/'+companyId, dataType: "json", type: 'GET' })
}).then(function(message) {
return message;
}, function(error) {
console.log( error );
});
}
});
My route and template is loading fine, when I navigate to app/portfolio/company/1, but for some reason when I navigate to that route, Ember wont load the model (no error, but the {{model}} variable does not get populated in template). Only when I refresh the page, Ember loads the model?! I am a bit confused now...
Edit: added missing param and added better description
I think in your template or in controller you are using model like so
model.company replace it with model, and remove extraneous RSVP.hash
because Ember.$.ajax already returns promise which model hooks can handle
so in ES6 (ember-cli supports it) your model hook should look like this
model({ id }) {
return Ember.$.ajax('/api/company/' + id);
}
with above things everything should work, what was happening I think you were passing just model to {{link-to}} while your controller or template expecting model.company so was breaking things

Calling controller method from controller action in Ember 2.0

Ember 2.0 is really giving me a hard time to understand the new functionality. I want to call a method in the controller from the action function, but dont seem to find a way how. Wasted some time on this already
I have read this: calling method from action of controller in emberjs but it is only working for Ember 1.x as in Ember 2.0 there is no ArrayController anymore and I cannot use this.send().
Basically what I would need is:
App.SomeController = Ember.Controller.extend({
methodFunction: function(data) {
console.log("YEY", data);
}
actions: {
sessionAction: function(data) {
this.methodFunction(data);
}
}
});
Problem is that this.methodFunction is not available
Code you've provided in question has an error:
SyntaxError: controllerName.js: unknown: Unexpected token (7:3)(…)
You're missing , after methodFunction declaration. Fix:
App.SomeController = Ember.Controller.extend({
methodFunction: function(data) {
console.log("YEY", data);
},
actions: {
sessionAction: function(data) {
this.methodFunction(data);
}
}
});
For template:
<button {{action 'sessionAction' 'Example data'}}>Send session action</button>
It logs correctly:
YEY Example data
By the way, you can also take advantage of ES2015 syntax:
export default Ember.Controller.extend({
methodFunction(data) {
console.log("YEY", data);
},
actions: {
sessionAction(data) {
this.methodFunction(data);
}
}
});
Working demo.
Full code behind demo.

Assertion Failed: The value that #each loops over must be an Array error. What am I doing wrong?

I am following Ember's TodoMVC tutorial and I am stuck. Basically, I defined 2 controllers. This is todos.js
import Ember from "ember";
export default Ember.ArrayController.extend({
actions:{
createTodo: function(){
var title = this.get("newTitle");
if(!title){
return false;
}
if(!title.trim()){
return;
}
var todo = this.store.createRecord("todo", {
title: title,
isCompleted: false
});
// Clear text field
this.set('newTitle', '');
todo.save();
}
}
})
This is todo.js
import Ember from "ember"
export default Ember.ObjectController.extend({
isCompleted: function(key, value){
var model = this.get("model");
if(value === undefined){
return model.get("isCompleted");
} else {
model.set('isCompleted', value);
model.save();
return value;
}
}.property('model','model.isCompleted')
});
Here is routes/todos.js
import Ember from "ember";
export default Ember.Route.extend({
model: function() {
return this.store.find("todo");
}
});
Finally, also defined todos.hbs
<ul id="todo-list">
{{#each todo in model itemController="todo"}}
<li {{bind-attr class="todo.isCompleted:completed"}}>
{{input
type="checkbox"
class="toggle"
checked=todo.isCompleted
}}
<label>{{todo.title}}</label><button class="destroy"></button>
</li>
{{/each}}
</ul>
Everything looks good, but I am getting the following error in the console:
Uncaught Error: Assertion Failed: The value that #each loops over must
be an Array. You passed todomvc-embercli#controller:array:, but it
should have been an ArrayController
What am I doing wrong here?
As per turboMaCk's comment, removing ember-disable-proxy-controllers from package.json seems to fix the issue.
This issue was just reported yesterday on the Ember GitHub page. It seems to be a bug with Ember and I don't know of a workaround. However, it does mention that you can use components instead of a array and item controllers (which is the preferred method anyway). Maybe try looking at this gist that was posted in the issue.
I'll come back and update this answer if a workaround/fix is found. For now, I would say try to avoid array controllers (even though it's in the tutorial). :/

Ember CLI + Ember Data + Simple Auth: authorize gets not called

i am using Ember CLI + Ember Data + Simple Auth. The authenticator is working fine. But when im am doing a Rest Call with Ember Data Rest Adapter this.store.findAll("user"); the authorize function in my custom authorizer don't gets called.
The Rest API Endpoint is on an other domain, so i added the url to the crossOriginWhitelist in my environment.js.
environment.js:
module.exports = function(environment) {
var ENV = {
// some configuration
};
ENV['simple-auth'] = {
crossOriginWhitelist: ['http://api.xxxx.com'],
authorizer: 'authorizer:xxxx',
routeAfterAuthentication: 'dashboard',
};
return ENV;
};
authorizer
import Ember from 'ember';
import Base from 'simple-auth/authorizers/base';
var XXXXAuthorizer = Base.extend({
authorize: function(jqXHR, requestOptions) {
// Some Code, gets not called, damn it :(
}
});
export default {
name: 'authorization',
before: 'simple-auth',
initialize: function(container) {
container.register('authorizer:xxxx', XXXXAuthorizer);
}
};
index.html
....
<script>
window.XXXXWebclientENV = {{ENV}};
window.ENV = window.MyAppENV;
window.EmberENV = window.XXXXWebclientENV.EmberENV;
</script>
<script>
window.XXXXWebclient = require('xxxx-webclient/app')['default'].create(XXXXWebclientENV.APP);
</script>
....
Thanks for help :)
I had a similar problem. For me it was the crossOriginWhitelist config.
I set it like this:
// config/environment.js
ENV['simple-auth'] = {
crossOriginWhitelist: ['*'] // <-- Make sure it's an array, not a string
};
to see if I could get it working (I could), then I could narrow it down to figure out exactly what URL I should use to enforce the restriction (port number and hostname etc).
Don't leave it like that though!
You should actually figure out what URL works for the whitelist, and use that.
I am facing the same issue. I have same setup but the authorize function is not being called. May be you can try by adding the port number in your crossOriginWhiteList url.
I am adding window.ENV = window.MyAppENV line in new initializer which runs before simple-auth. You have added that in index file and may be that is the reason why simple-auth is not able to read your configuration.
Does the other configuration routeAfterAuthentication: 'dashboard', works properly? If not then this might be the reason. Try adding new initializer like
export default {
name: 'simple-auth-config',
before: 'simple-auth',
initialize: function() {
window.ENV = window.MyAppNameENV;
}
};

Categories

Resources