Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect URL change and grab URL in EmberJS (using Discourse)

I'm using Discourse (http://www.discourse.org/), which is built on EmberJS, and trying to observe any time the URL changes, e.g. when opening a new topic. I've seen the answer for observing the currentPath, for example here: Detect route transitions in EmberJS 1.0.0-pre.4

App.ApplicationController = Ember.Controller.extend({

  routeChanged: function(){
    // the currentPath has changed;
  }.observes('currentPath');
});

But I'm trying to detect any URL change, not just a path change. As mentioned in the comments for that answer:

This observer doesn't fire when transitioning from for example /pages/1 to /pages/2 because the path is staying the same: pages.page.index

What I'd like to do is actually detect those aforementioned transitions which don't get triggered by observes('currentPath'). Along those lines, if I do this.get('currentPath'); inside of my function, I get something like topic.fromParams but I actually am interested in the URL path e.g. /t/this-is-my-url-slug.

To put it simply, I'd like to detect when the app goes from:

/t/this-is-my-url-slug

to

/t/another-url-slug

and be able to capture the path: /t/another-url-slug

Sorry but I'm a bit of an Ember n00b and my only experience with it is through Discourse. Any ideas?

like image 350
kaptron Avatar asked Dec 26 '22 03:12

kaptron


1 Answers

You don't need anything Ember-specific to do this. Depending on whether you are using hash or pushstate, you can use...

$(window).on('hashchange', function(){
  console.log("Hash URL is " + location.hash.substr(1));
  // Do stuff
});

or

$(window).on('popstate', function(e) {
  console.log("Hash URL is " + window.location.pathname);
  // Do stuff
});
like image 85
Luke Melia Avatar answered May 12 '23 11:05

Luke Melia