Emberjs - Can I set controller in View inside didInsertElement? - ember.js

I am new to EmberJS and have existing code.
I have a login form which should be posted on hitting enter button.
First time everything goes smooth and working as expected, once I log out- it clears the session and redirects me to login view and then the problem starts as that.get("controller") is undefined this time.
My Login view is having below code
didInsertElement: function () {
var that = this;
Ember.$(document).keyup(function (e) {
if (e.which == 13) {
that.get("controller").send("login");
// **As that.get("controller") is undefined I want to set that**
//that.set("controller"); //- **CAN I DO THIS?**
}
});
}
My problem is - that.get("controller") is undefined.
When I tried that.set("controller"); - it says that
Assertion Failed: calling set on destroyed object

Related

Ionic 2 page navigation not working

Trying to navigate from the starting page (i'm using a side menu rather than tabs).
The navigation seems to work, but only after pressing the button twice (the old pages does not leave the DOM, but the new pages constructor fires, and replaces the header to the page. I can then press the navigate button again, which re-runs it's page logic and renders the rest of the page. I've attached some screenshots:
This is the main login:
After pressing the button to login, the next pages logic runs, and the header changes. But the old page doesn't leave.
I can press login again, the next pages logic runs again then it renders the page.
Here's the code:
login(){
this.refToProgram.loggedIn = true;
this.nav.push(NearmePage).then(
response => {
console.log('Response ' + response);
},
error => {
console.log('Error: ' + error);
}
).catch(exception => {
console.log('Exception ' + exception);
});
}
The result of this is: 'Response true'
Which means ionic thinks the navigation was successful, what am I missing?
try to navigate with [navPush]= "nearmePage"; Inside the login button
Inside your controller
Insert the nearmePage class and the inside your LoginPage class
declare nearmePage = "NearmePage" so that will take to the respected page form login page

EmberJS - promise returned by transitionToRoute is not resolved when the transition is aborted and retried

I have an action in PostController which has the following code.
var self = this;
this.transitionToRoute('post').promise.then(function(){
self.set('isEditing', true);
});
But, inside the PostRoute's willTransition action I have a logic to check for dirtyComment and abort the transition and ask for user confirmation, and depending on the user input, will retry the transition or leave the transition as aborted and do nothing. I need this logic to reside in willTransition of PostRoute because, this check needs to be performed whenever a user tries to transition out of the /post route.
willTransition: function(transition) {
if (this.controller.get('isCommentDirty')){
transition.abort();
if(confirm("Are you sure you want to abort the comment?")) {
// If the user confirms perform some logic
transition.retry();
}
} else{
// Bubble the `willTransition` action so that
// parent routes can decide whether or not to abort.
return true;
}
}
Now, when the comment is dirty and the transition is aborted and retried, the promise is not full filled. I know this happens because retry creates a completely new Transition object. But, is there a workaround for this?
Also, what I do not understand is if ember should actually deal with this?
I resolve similar situation (auth checking) using an another one promise, which I've fully control. It's not your case though.
You can invert the behavior by ether creating post.edit route or moving conformation logic to the controller (not route) like this:
In PostController:
var self = this,
isCommentDirty = this.get('isCommentDirty');
if (isCommentDirty && confirm("Are you sure you want to abort the comment?")) {
this.transitionToRoute('post').then(function(){
self.set('isEditing', true);
});
}
or
var self = this,
isCommentDirty = this.get('isCommentDirty');
if (isCommentDirty && confirm("Are you sure you want to abort the comment?")) {
this.set('isEditing', true);
this.transitionToRoute('post');
}
By the way. If you want to restrict an editing of dirty comments, you can hide 'edit' button in a template. For that case, with 'post.edit' route, code in PostController would be:
if (confirm("Are you sure you want to abort the comment?")) {
this.transitionToRoute('post.edit');
}

Reload model/update template on createRecord save

I see this question is being ask all over again still don't find solution that works for such a trivial task.
This url displays a list of navigations tabs for workspaces.
http://localhost:4200/users/1/workspaces
Each of tab resolves to
http://localhost:4200/users/1/workspaces/:wid
Also on the I have a button that suppose to create a new workspace as well as new tab.
Here how controller for looks:
export default Ember.Controller.extend({
actions: {
newWorkspace: function () {
this.get('currentModel').reload();
var self = this;
var onFail = function() {
// deal with the failure here
};
var onSuccess = function(workspace) {
self.transitionToRoute('dashboard.workspaces.workspace', workspace.id);
};
this.store.createRecord('workspace', {
title: 'Rails is Omakase'
}).save().then(onSuccess, onFail);
}
}
});
When I click on button I see in ember inspector new record indeed created as well as url redirected to id that represents newly created workspace.
My question is how to force model/template to reload. I have already killed 5h trying model.reload() etc. Everything seem not supported no longer. Please please help.
UPDATE
When adding onSuccess
model.pushObject(post);
throws Uncaught TypeError: internalModel.getRecord is not a function
I believe you should call this.store.find('workspace', workspace.id) for Ember Data 1.12.x or earlier. For 1.13 and 2.0 there are more complicated hooks that determine whether or not the browser should query the server again or use a cached value; in that case, call this.store.findRecord('workspace', workspace.id, { reload: true }).
I do not know if this help. I had a similar problem. My action was performed in the route. Refresh function took care of everything.

Ember Data creates local record on GET that returns 404

When I request a single resource that returns a 404 (or 403 for that matter) Ember Data is creating a local record.
For example, I load my app from scratch at /items/123. The adapter does a request for GET /items/123 which results in a 404 but now I have an item record in my local store with id=123. All attributes are undefined expect where the model defines default values.
Also, all model flags are false except isValid which is true.
Is this excepted behaviour? It seems strange that the local record gets created even though the server is saying that it doesn't exist (or that the user is not allowed to see it).
Details
I'm running Ember 1.8.1 and Ember Data 1.0.0-beta.11.
Here's what I have for Routes—pretty basic stuff:
// itemsRoute, TOP LEVEL
model: function() {
return this.store.find('item');
}
// itemRoute, CHILD LEVEL
model: function(params) {
return this.store.find('item', params.item_id); // <-- this returns 404
},
actions: {
error: function(err) {
this.replaceWith('items'); // jump out to main list view
return true; // ensure error bubbles up
}
}
The rejection in the model hook is working because the error action is triggered and I'm redirected out the top level /items view. But I still end up with a local record for an item that doesn't exist.
After thinking about this a little more... try altering your error handler in itemRoute from...
actions: {
error: function(err) {
this.replaceWith('items'); // jump out to main list view
return true; // ensure error bubbles up
}
}
to...
actions: {
error: function(err) {
this.transitionTo('items'); // jump out to main list view
return false; // Stop event bubbling - we've handled it.
//You could also console.log parts or all of your error
//You can return true too if you want to keep the event bubbling.
}
}
I don't have a concrete reason for why this would be yet. Waiting to hear back from you if it worked.
This is most definitely a bug. It seems this was fixed a while back but as was reintroduced by a change on March 14.
I've submitted a bug report https://github.com/emberjs/data/issues/3085

How to client side authentication with Emberjs

First of all I don't use Ruby nor Devise :) (all my searches led me to plugins that kind of rely on Devise)
I want to do pretty simple authentication with Ember, I have a REST backend that blocks requests without a proper cookie(user-pass) and i want Ember to watch when it gets 403 forbidden (won't let you to transition into protected URLs) and then pop up a user-login dialog.
So when a user tries to send a new message for example(lets say i've built a forum) Ember will fire the request and if it gets 403 it will block the transition and popup a login form and will retry the transition after the login have completed
Also is there a way to get the errors from ember-data and respond to them? (if a user tries to change an attribute he can't access i would like to inform him about it[Access denied or something like that])
I want to use custom errors that my server will send to ember data not just error numbers but words like "Sorry you can't change this before 12 PM"
You can simply listen to the response of your server and transition to your LOGIN (or whatever you call it) route. In my apps I happen to keep two types of routes (LOGIN and AUTHENTICATED). When they access the authenticated routes without logging in, they get a 401 unauthorized error and get transitioned to the LOGIN route.
// AuthenticatedRoute.js
redirectToLogin: function(transition) {
// alert('You must log in!');
var loginController = this.controllerFor('login');
loginController.set('attemptedTransition', transition);
this.transitionTo('login');
},
events: {
error: function(reason, transition) {
if (reason.status === 401) {
this.redirectToLogin(transition);
} else {
console.log(reason);
window.alert('Something went wrong');
}
}
},
model: function () {
return this.store.find('post');
},
So now when the user requests for post he gets a 401 and gets transitioned to LOGIN controller.
// LoginController.js
login: function() {
var self = this, data = this.getProperties('username', 'password');
// Clear out any error messages.
this.set('errorMessage', null);
$.post('/login', data).then(function(response) {
self.set('errorMessage', response.message);
if (response.success) {
alert('Login succeeded!');
// Redirecting to the actual route the user tried to access
var attemptedTransition = self.get('attemptedTransition');
if (attemptedTransition) {
attemptedTransition.retry();
self.set('attemptedTransition', null);
} else {
// Redirect to 'defaultRoute' by default.
self.transitionToRoute('defaultRoute');
}
}
});
}
The basic answer you need is capturing the events in the route and transitioning accordingly. I just happened to include the code for attempted transition as it comes in handy at times.