Is it advisable and what is the proper way to shift to a different route within a promise's

Trying to utilize Ember controller to make an API call for user creation and then transitionToRoute upon success. Here is the current setup:

import ajax from "ic-ajax";
import Ember from "ember";

export default Ember.Controller.extend({
  actions: {  
    createAndLoginUser: function() {
      var user = { "user": this.getProperties("email", "name") };
      ajax({ url: "api/users", type: "POST", data: user })
        .then(transitionToHome);
    }   
  }
});

var transitionToHome = function() {
  this.transitionToRoute("home")
}

However, encountering issues with scope when placing a debugger in the method as this no longer refers to the controller object, causing problems with calling transitionToRoute.

Primarily accustomed to informal javascript, attempting to grasp foundational concepts and frameworks. Is this approach correct for handling promises, and is the location within Ember appropriate for transitioning?

Answer №1

Your issue is not related to Ember or transitions; it's all about how you handle 'this'. The easiest solution is:

.then(transitionToHome.bind(this));

Placing transition method in the controller

You could also opt to place 'transitionToHome' inside the controller as a method. Then, you can call it like this:

export default Ember.Controller.extend({

  transitionToHome: function() { this.transitionToRoute("home"); },

  actions: {  
    createAndLoginUser: function() {
      var self = this;
      var user = { "user": this.getProperties("email", "name") };
      ajax({ url: "api/users", type: "POST", data: user })
        .then(function() { self.transitionToHome(); });
    }   
  }

});

This approach may be simpler, more readable, and eliminates the need to deal with 'this' and using 'bind' (though it requires the use of 'self').

Considering moving the transition to the route?

Although beyond your current question, some argue that route-related operations (including transitions) should logically reside in the route instead of the controller. If you agree with this view, you could restructure the code by utilizing 'send':

createAndLoginUser: function() {
  var user = { "user": this.getProperties("email", "name") };
  var self = this;
  ajax({ url: "api/users", type: "POST", data: user })
    .then(function() { self.send("goHome"); });
  }
}

You can then implement the 'goHome' action in your route. Alternatively, you can define 'goHome' in a higher-level route, potentially even the application route, making it accessible from any controller or lower-level route.

Considering moving the AJAX logic to a service?

Some argue that the AJAX logic doesn't belong in the controller and should be housed in a services layer. In this case, it might look something like this:

// services/user.js
export function createUser(data) {
  return ajax({ url: "api/users", type: "POST", data: { user: data } });
}

// controller
import { createUser } from 'app/services/user';

export default Ember.Controller.extend({
  createAndLoginUser: function() {
    var data = this.getProperties("email", "name"));
    var self = this;
    createUser(data).then(function() { self.send("goHome"); });
  }
};

Utilizing ES6 syntax allows us to remove the need for 'self,' making the code a bit cleaner:

createAndLoginUser: function() {
    var data   = this.getProperties("email", "name"));
    var goHome = () => this.send("goHome");

    createUser(data).then(goHome);
  }

With these changes, the code becomes more coherent and easier to understand.

Answer №2

A simple yet effective approach is to utilize ES6 arrow function syntax for preserving the context of this:

import ajax from "ic-ajax";
import Ember from "ember";

export default Ember.Controller.extend({
  actions: {  
    createUserAndLogin() {
      let user = { "user": this.getProperties("email", "name") };
      ajax({ url: "api/users", type: "POST", data: user })
        .then(() => {
          this.transitionToRoute("home");
        });
    }   
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate additional libraries like jQuery into your Vue.js application

I am facing an issue with connecting a third-party js library to a vue.js component main.js ... require('jquery') import Vue from 'vue' import VueMdl from 'vue-mdl' import App from './App' import Auth from './ ...

How can I design a versatile button in HTML/CSS3/jQuery/Javascript that utilizes images for borders and corners for maximum scalability?

Is there a way to create a completely scalable button in HTML/CSS3/jQuery+Plugins using images for borders and corners? I have attempted a messy method, but I am confident that there are more effective solutions available. The approach I considered invol ...

carousel initialization failed due to materialization error

I am experiencing a peculiar issue with the carousel feature on a website built using MaterializeCSS. Sometimes it functions correctly, but other times I encounter the following error: jQuery.Deferred exception: c is undefined s@https://cdnjs.cloudflare.c ...

How to retrieve data from a nested object within a JSON array using JavaScript

When I use Logger.log(response.data.phone), the following data is displayed in my log: [{label=work, primary=true, value=5558675309}, {label=work, value=6108287680, primary=false}, {value=6105516373, label=work, primary=false}] My goal is to have the two ...

Leveraging context and hooks in React JS

Once again, I find myself here. Just 3 hours ago I was struggling with understanding how to use Context and useState in React. Thankfully, I managed to solve that issue on my own. However, now I'm facing another challenge - this time it's about s ...

Using the HttpPut method in conjunction with a route controller

Hey there, I could really use some assistance. I'm currently attempting to utilize the PUT Method via AJAX in order to send data to a controller for an update operation. Here's my JavaScript and AJAX code: function UpdateProduct() { var id = loc ...

The persistent Expo in-app purchase sandbox pop-up continues to plague, hindering the completion of the test purchase

After creating my app using Expo and integrating Revenuecat for payments, I encountered an issue while testing it. Whenever I try to subscribe, the purchase popup keeps reappearing in Sandbox mode even after clicking 'Done'. Despite entering vali ...

When there is no content in the responseText, AJAX will display an error

I've encountered an issue while trying to fetch data using AJAX. The problem lies in receiving an empty responseText. Here's the code I'm working with: JavaScript: function getFounder(id) { var founder = ""; $.ajax({ ...

How does Sizzle JS function?

While investigating the sizzle.js source code for a project, I stumbled upon an interesting discovery. Towards the end of the code, there is a line that reads: window.Sizzle = Sizzle; However, there doesn't seem to be any declaration of a variable n ...

Unlimited POST requests on Safari 7

I'm facing a challenging issue that has me stuck. I have a form where users submit their data, triggering a post ajax request. Upon success, I populate some data in a hidden form with an action pointing to the current subdomain URL, but actually redir ...

AngularJS's angular.element is currently accessing the current Document Object Model

While experimenting with angular.element, I was curious about accessing the current DOM from an ng-click event. Is there a way to do this? For example: <div ng-click="angular.element(curElement).parent()..."></div> How can I retrieve the cur ...

What is the best way to sort through the items in a dropdown menu?

Can you help me with a scenario where I need to filter elements in a dropdown based on input given in a text box? I have tried using ng-change but it doesn't seem to work. Is there another way to achieve this? Here is the HTML code snippet: <inpu ...

What is the process of transferring information from a form to mongodb?

I have created a nodejs project with the following structure: https://i.stack.imgur.com/JiMmd.png api.js contains: const express = require('express'); const router = express.Router(); const add = require('../model/myModel'); router.g ...

Is there a way to improve error readability in React when using webpack?

Attempting to solve the issue, I decided to make a change in my npm script. Initially, it was set to operate in production mode by default: The original script looked like this: "client": "webpack -w --config ./gen/config/webpack.config.js& ...

The error message states: "Dygraph is not defined."

Currently, I am utilizing express.js in my application to render dygraph charts on the client side. You can take a look at my index.jade file here. Upon visiting my browser, an error pops up in the console: Uncaught ReferenceError: Dygraph is not defined. ...

How can I prevent the menu from being hidden when I click on it in jQuery?

I'm currently working on the following code that is functioning perfectly: /* ** SHOW OR HIDE A MENU BASED ON CLICK LOCATION */ function showBasket(){ var $basket=$('#basket'); var nstyle=$basket.css("display"); if (nstyle==&apo ...

Change the location of an html td element with JavaScript

I am currently working on a simple JavaScript car racing game where the cars are represented by HTML table elements. I want to implement functionality where pressing the "e" key moves player one's car and the "d" key moves player two's car. This ...

Does Typescript not provide typecasting for webviews?

Typescript in my project does not recognize webviews. An example is: const webview = <webview> document.getElementById("foo"); An error is thrown saying "cannot find name 'webview'". How can I fix this issue? It works fine with just javas ...

The secondary angular button is failing to execute the function

Can someone help me with a small issue? I have two buttons on a webpage that should both contact a server. However, only the first button sends a HTTP request when clicked. <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8 ...

Guide to utilizing $.when in node.js?

Is there a way to send multiple ajax requests simultaneously in node.js and have a single callback for all of them? I found a solution using jQuery here: Pass in an array of Deferreds to $.when(), but I'm not sure how to achieve this in node.js. Any s ...