How to make an array of objects global in ember.js?

Member

by lottie , in category: Javascript , 3 months ago

How to make an array of objects global in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 3 months ago

@lottie 

To make an array of objects global in Ember.js, you can define the array in the app/controller/application.js file and export it as a global variable using window object.


Here's an example of how you can do this:

  1. Define the array in app/controller/application.js:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import Controller from '@ember/controller';

let globalArray = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' }
];

export default Controller.extend({
  init() {
    this._super(...arguments);
    window.globalArray = globalArray;
  }
});


  1. Access the global array in other components or routes by using window.globalArray:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// app/components/some-component.js

import Component from '@ember/component';
import { computed } from '@ember/object';

export default Component.extend({
  globalArray: computed(function() {
    return window.globalArray;
  })
});

// app/routes/some-route.js

import Route from '@ember/routing/route';

export default Route.extend({
  model() {
    return window.globalArray;
  }
});


By defining the array as a global variable using the window object, you can access it from any component, route, or controller in your Ember.js application. Just make sure to handle the array properly to avoid any unexpected behavior or bugs.