Skip to main content

How I solved programmatically updating window.location from a child element in a subroute using events and app-route



I was having trouble figureing out how to programaticlly change window.location 
from a nested child element. In my case I wanted to send up a uri from dropdown.  
The `select-item` property was bound to  `location`, and `location` had an 
observer `_updateLocation`. 
        <x-dropdown selected-item={{location}}></x-dropdown>
            observer: '_updateLocation' 
I could have set `notify:true` on `location`, but then I would have to pass it 
up the chain. Instead I decided to use an event. 
        _updateLocation: function(item){
  'update-location-request', {
On the element that contians the `app-location` I set up a property called `location`
,it also has an `observer:'_updateLocation'` (these don't have to be named the same 
as on the child, it just worked out that way), . Finally I set up a listener for
        <app-location route="{{route}}" use-hash-as-path></app-location>
            type: String,

        _setRoute: function(){
            this.set('route.path', this.location)
        _updateLocation: function(e) {
          // will not call `_setRoute` more than once per 100ms
          this.debounce('update-location', function() {
          }, 100);
        ready: function(){
            this.addEventListener('update-location-request', function(e){
                this.location = e.detail.uri


The `debounce` allows things to catch up. It is `debounce` that makes this all work. 
With out it when you use the back button things get wonky, when a subroute triggers 
load of the drop down on the way back in browser history `location` get changed 
mulitple times and `debounce` restores some sanity.

The gist can be found here 
Post a Comment

Popular posts from this blog