Skip to content

Commit

Permalink
fix: URL changes so fast
Browse files Browse the repository at this point in the history
fixes #252
  • Loading branch information
RomanHotsiy committed May 12, 2017
1 parent cb106cc commit 131b437
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/services/hash.service.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
'use strict';
import { Injectable } from '@angular/core';
import { PlatformLocation } from '@angular/common';

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { debounce } from '../utils/';

@Injectable()
export class Hash {
public value = new BehaviorSubject<string | null>(null);
private noEmit:boolean = false;
private debouncedUpdate: (hash:string, rewrite: boolean) => void;

constructor(private location: PlatformLocation) {
this.bind();

this.debouncedUpdate = debounce(this._update.bind(this), 100);
}

start() {
Expand All @@ -28,6 +33,10 @@ export class Hash {
}

update(hash: string|null, rewriteHistory:boolean = false) {
this.debouncedUpdate(hash, rewriteHistory);
}

private _update(hash: string|null, rewriteHistory:boolean = false) {
if (hash == undefined) return;
if (rewriteHistory) {
window.history.replaceState(null, '', window.location.href.split('#')[0] + '#' + hash);
Expand All @@ -39,4 +48,5 @@ export class Hash {
this.noEmit = false;
});
}

}
15 changes: 15 additions & 0 deletions lib/utils/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,21 @@ export function throttle(fn, threshhold, scope) {
};
}

export function debounce(func, wait, immediate = false) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}

export const isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0
|| (function (p) { return p.toString() === '[object SafariRemoteNotification]'; })(!window['safari']
|| safari.pushNotification);
Expand Down

0 comments on commit 131b437

Please sign in to comment.