Is Ember the ideal spot for shared ownership?

Currently, I am developing a hybrid app that involves server processing and using Ember for the main UI implementation.

All authentication functionalities are handled on the server side, so upon page load, the user's authentication status is already determined based on cookies.

In essence, on the client-side, there exists a userId cookie, which signifies whether the user is authenticated or not.

Now, the challenge lies in making this data accessible to all templates within the application.

I managed to resolve this issue for the application template through the following code snippet (implemented in CoffeeScript):

Route:

ApplicationRoute = Ember.Route.extend
  setupController: (controller) ->
    userId = jQuery.cookie 'userId'
    if userId == 'undefined'
      userId = null
    else
      userId = parseInt userId, 10
    controller.set 'userId', userId

Controller:

ApplicationController = Ember.Controller.extend
  userId: null

Finally, the template:

<strong>
  {{#if userId}}
    userId: {{userI	}}
  {{else}}
    No user
  {{/if}}
</strong>

While this solution works seamlessly from the application template, any attempt to move it to another template like the index results in displaying 'no user' (indicating issues with controller chaining).

I also experimented with converting it into a bound helper but encountered difficulties as the helper failed to execute at all:

Ember.Handlebars.registerBoundHelper 'userId', ->
  userId = jQuery.cookie 'userId'
  if userId == 'undefined'
    userId = null
  else
    userId = parseInt userId, 10
  userId

Answer №1

When faced with a situation where I needed to handle asynchronous setup logic before initializing my Ember application, I found that using App.deferReadiness() and App.advanceReadiness(), along with setting global properties directly on the App object, was the most effective solution.

The Ember API documentation for deferReadiness() states:

This method can be used to delay the readiness of the application until a certain condition is met.

For instance:

   App = Ember.Application.create();
   App.deferReadiness();

   jQuery.getJSON("/auth-token", function(token) {
     App.token = token;
     App.advanceReadiness();
   });

By employing this technique, you can execute asynchronous setup tasks and postpone the initialization of your application until these tasks are completed.

One practical example involves retrieving the user's ID from a cookie prior to launching Ember, and storing it in App.currentUser:

App = Ember.Application.create({});

App.deferReadiness();

var userId = "1234";//jQuery.cookie 'userId'
if (userId == 'undefined') {
  userId = null;
  App.set('currentUserLoggedIn', false);
  //window.location = "/login"; // redirect to login page
} else {
  userId = parseInt(userId, 10);
  App.set('currentUserLoggedIn', true);
  App.set('currentUser', userId);
  App.advanceReadiness();
}

This value can then be accessed throughout the application using:

App.get('currentUser');

or in templates:

{{App.currentUser}}

Check out this JSBin example for further clarification.

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

Angular will move the input field cursor to the beginning after typing 4 digits

I'm looking for some guidance with a specific scenario involving a reactive form input field. The field is meant to capture the last four digits of a Social Security Number (SSN), and upon filling it out, an API call is triggered to validate the enter ...

Displaying a dropdown selection that showcases two object properties lined up side by side

I need the select option dropdown values to display employee names along with their titles in a lined up format. For instance, if my values are: Bob Smith Director Mike Kawazki HR Jane Doe Manager I want them to be shown as: Bob Smith Director Mi ...

Using AJAX to pass the ID name when clicking in PHP

Currently, I am in the process of implementing an Ajax-driven filtered search system that consists of three distinct tabs. These tabs allow users to search by names, category, and location. I have successfully enabled searching when a user types a name int ...

Is there a way to terminate an ongoing axios request?

I have been encountering a memory leak issue whenever my browser is redirected away from this component. To resolve this, I tried to cancel it using the cancel token, but unfortunately, it doesn't seem to be working as expected. I am puzzled as to why ...

The Flask AJAX request is returning an empty ImmutableMultiDict, whereas the same AJAX request successfully works with http.server

Making the switch from http.server to Flask has caused issues with my image upload functionality using AJAX. This is being done in Python 3. Attempts at troubleshooting that have failed: I have ensured multipart/form-data is included in the Ajax req ...

The user's display name in Firebase is currently empty

Running the following code in my react app: componentDidMount() { modelInstance.addObserver(this); modelInstance.getSignInStatus().then((user)=>{ this.setState({ userName: user !== false ? user.displayName : "Sign in", l ...

What could be the root cause behind this Selenium mistake?

My goal is to verify the correct scroll position in the browser using NightwatchJS and Selenium. Below is the command I am using in Nightwatch: assertScrollPosition(testValue) { this.api.execute(() => { const offsetValue = w ...

Utilize Javascript to interpret a structure that resembles JSON

My data resembles JSON, with columns and names listed: columns: [ { allowNull: false, autoEnterSubType: 0, autoEnterType: 2, creationOrderIndex: 0, dataType: 4, databaseSequenceName: "seq_admintraties_adminratie_id", flag ...

Filtering multiple rows in a table using Javascript

I'm currently working on creating a filter that can filter based on multiple inputs, with each input filtering in a separate column. Here is the JavaScript & code I am using: function myFunction(column, input) { var filter, table, tr, td, i, t ...

Discovering dependencies for the Tabulator library can be achieved by following these

Can anyone provide me with a complete list of dependencies for Tabulator 4.2? I have already reviewed the package.json file, but it only contains devDependencies. ...

Is the ngShow directive dependent on the parent variable in any way?

There is a piece of code running in the $rootScope to establish a global value for userLoggedIn: mod.run(function($rootScope) { $rootScope.userLoggedIn = false; $rootScope.$on('loggedIn', function(event, args) { $rootScope.userL ...

contentScript encountering CORS problem while using $.ajax()

I encountered an issue with the $.ajax() function not working in my contentScript. The error message I received was: XMLHttpRequest cannot load http://example.com/tab/index.php. No 'Access-Control-Allow-Origin' header is present on the request ...

What is the best method for transmitting data to HTML using Node.js?

I retrieved the database data using nodejs and now I need to display it in an HTML file. What steps should I take? Here is my app.js code: var express = require('express'); var router = express.Router(); router.get('/', function(re ...

Steps to configure caching settings to ensure no caching for the entire site during specific hours, and constant no-cache policy for a particular page

Managing cache for my website has become quite the challenge. Some pages need to be cached during certain hours to improve navigation speed, while others must not be cached during crucial data update times. And to add to the complexity, there are pages tha ...

Automate the population of input fields

I am working on a React application that utilizes Bootstrap. I have an input field that I want to automatically fill with a name when the user clicks a button. Initially, this input field should be empty, as the variable name = "". When the butto ...

How to align two <select> elements side by side using Bootstrap

The issue I am encountering is that these two select elements within the same control-group are being displayed vertically when I want them to be displayed horizontally. I attempted using inline-block in CSS, but there are other <div> elements with ...

Is there a way to access fields from an associated model within React components?

Is there a way to access fields from an associated model in React components within Rails? I have a listing model that I'm iterating through in a React component and retrieving all the fields for each record, including the ID of the associated model. ...

Is it possible to wait for two asynchronous actions using only one await statement?

I have a situation where I am dealing with a node module that exports a promise to resolve a database connection. Once this connection is resolved, I then need to use it to query records which involves another asynchronous operation. Is it possible to hand ...

Node Js issue stemming from unaddressed promises leading to rejection

Hi, everyone! I'm currently facing some challenges while trying to deploy this API. The error message I keep getting is: "UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error may have occurred due to either throwing inside an asyn ...

Scroll bar in Highstock does not completely cover the entire length when dealing with multiple series

Having trouble with the scrollbar on a multi-series line chart where the x-axis represents dates. It seems that the maximum length of the scrollbar is determined by the length of the first, older series. When clicking the 'All' button in the ran ...