0
votes

I am attempting to detect when a device changes it's orientation and update my component to reflect the new orientation.

The problem with my approach is that my event lives outside of the components life-cycle which in turn makes the component variable is undefined thus rendering the code inside the event absolutely useless.

Anyone that has some insight into what I could do to achieve this would great.

afterRender: function(component,helper){
    this.superAfterRender();
    window.addEventListener("orientationchange", function() {
        window.setTimeout(function(){
            if(window.innerWidth <= 768) {
                component.set('v.deviceWidth','small');
            } else if(window.innerWidth > 768 && window.innerWidth < 1440) {
                component.set('v.deviceWidth','medium');
            } else if(window.innerWidth >= 1440) {
                component.set('v.deviceWidth','large');
            }
        },500);
    });
}
1

1 Answers

0
votes

Good solution for you: https://github.com/ReactiveX/RxJS

Example here: https://golosay.net/rxjs-subjects/

Just create subject, and:

const sub = new Rx.Subject();
window.addEventListener("orientationchange", function() {
  sub.next(window.innerWidth)
});

In component:

sub.subscribe((value)=>{
 if(value <= 768) {
   c.set('v.deviceWidth','small');
 } else if(value > 768 && value < 1440) {
   c.set('v.deviceWidth','medium');
 } else if(value >= 1440) {
   c.set('v.deviceWidth','large');
 }
})

And don't forget unsubscribe when component will be destroy;