How to access Window & Document objects in Aurelia?

What is the best way to access Document and Window objects within ES6 / Aurelia ? I tried to access Window directly in my Aurelia code and it seems to work, but is this the right way or is there an Aurelia / ES6 way to do this?

In particular, I want to access properties such as window.localStorage and window .sessionStorage . I am just starting out with Aurelia and ES6, so I'm a little noob on how to do this, although I would like to follow the standards.

Something like the following:

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

This code does work in Aurelia, but is it correct to write it that way?

+5
source share
1 answer

This is the right way to do this in Aurelia when working with the web API, so that you are fine with the code that you have.

However, when working with the DOM, you can of course use the standard DOM API, but Aurelia has a platform abstraction layer ( PAL docs ) that will abstract any platform your application runs 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 does little at the moment, but in the future it is planned to allow you to work with your daily DOM API calls, even if your application cannot work in a β€œnormal” DOM.

It is very important not to forget that the native DOM and web APIs are really powerful, and there is nothing wrong with using their own implementations. Other structures typically build their own implementation around a web API that is adapted to the structures and best practices of their infrastructures, but this is not always the best thing.

+11
source

Source: https://habr.com/ru/post/1243552/


All Articles