ghiscoding ghiscoding - 1 month ago 8
Javascript Question

How to access Window & Document objects in Aurelia?

What is the best way to access

Document
and
Window
objects in
ES6
/
Aurelia
framework? I did try accessing
window
directly in my Aurelia code and it does seem to work, but is that the proper way or is there an Aurelia/ES6 way of doing that?

Specifically, I want to access properties like window.localStorage and window.sessionStorage. I'm just starting with Aurelia and ES6, so I'm a little noob on how to do this one though I would like to follow the standards.

Something like the following:

constructor() {
this.user = JSON.parse(window.sessionStorage.user || window.localStorage.user);
}


That code actually work in Aurelia, but is that correct to write it this way?

Answer Source

That is the correct way to do it in Aurelia when working with Web APIs, so you're fine with the code you currently have.

However, when working with the DOM you can of course use the standard DOM API as well, but Aurelia has a Platform Abstraction Layer (PAL docs) that will abstract whatever platform your application resides on with a DOM-like API.

For example, the equivalent of document.getElementById would be

import {inject} from 'aurelia-framework'
import {DOM} from 'aurelia-pal'

@inject(DOM)
export class Home {
  constructor(DOM) {
    this.DOM = DOM
  }

  attached() {
    let element = this.DOM.getElementById('someId')
  }
}

Unfortunately, PAL isn't really doing much at the moment but in the future it is planned to allow you to work with your everyday DOM API calls even though your application may not be running in a "normal" DOM.

One very important thing not to forget is that the native DOM & Web APIs are really powerful and there is nothing wrong with using their native implementations. Other frameworks tend to build their own implementation around the Web API's that is tailored to their frameworks' structures and best-practices but that is not necessarily the best thing.