fix: URL changes so fast

fixes #252
This commit is contained in:
Roman Hotsiy 2017-05-12 11:21:47 +03:00
parent cb106cc668
commit 131b437478
No known key found for this signature in database
GPG Key ID: 5CB7B3ACABA57CB0
2 changed files with 26 additions and 1 deletions

View File

@ -1,15 +1,20 @@
'use strict'; 'use strict';
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { PlatformLocation } from '@angular/common'; import { PlatformLocation } from '@angular/common';
import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { debounce } from '../utils/';
@Injectable() @Injectable()
export class Hash { export class Hash {
public value = new BehaviorSubject<string | null>(null); public value = new BehaviorSubject<string | null>(null);
private noEmit:boolean = false; private noEmit:boolean = false;
private debouncedUpdate: (hash:string, rewrite: boolean) => void;
constructor(private location: PlatformLocation) { constructor(private location: PlatformLocation) {
this.bind(); this.bind();
this.debouncedUpdate = debounce(this._update.bind(this), 100);
} }
start() { start() {
@ -28,6 +33,10 @@ export class Hash {
} }
update(hash: string|null, rewriteHistory:boolean = false) { update(hash: string|null, rewriteHistory:boolean = false) {
this.debouncedUpdate(hash, rewriteHistory);
}
private _update(hash: string|null, rewriteHistory:boolean = false) {
if (hash == undefined) return; if (hash == undefined) return;
if (rewriteHistory) { if (rewriteHistory) {
window.history.replaceState(null, '', window.location.href.split('#')[0] + '#' + hash); window.history.replaceState(null, '', window.location.href.split('#')[0] + '#' + hash);
@ -39,4 +48,5 @@ export class Hash {
this.noEmit = false; this.noEmit = false;
}); });
} }
} }

View File

@ -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 export const isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0
|| (function (p) { return p.toString() === '[object SafariRemoteNotification]'; })(!window['safari'] || (function (p) { return p.toString() === '[object SafariRemoteNotification]'; })(!window['safari']
|| safari.pushNotification); || safari.pushNotification);