为 window.location 附加更改通知程序 [英] Attaching change notifier for window.location
问题描述
每当 window.location.href 发生变化时,我都需要触发一个函数,但我遇到了问题.我查看了各种 watch
polyfills 的源代码,但我无法完全理解代码中发生的事情.
I need to trigger a function whenever window.location.href changes but I'm running into problems. I went over the source for various watch
polyfills, but I can't quite follow what was going on with the code.
if (!Object.prototype.watch) {
Object.defineProperty(Object.prototype, "watch", {
enumerable: false
, configurable: true
, writable: false
, value: function (prop, handler) {
var
oldval = this[prop]
, newval = oldval
, getter = function () {
return newval;
}
, setter = function (val) {
oldval = newval;
return newval = handler.call(this, prop, oldval, val);
}
;
if (delete this[prop]) { // can't watch constants
Object.defineProperty(this, prop, {
get: getter
, set: setter
, enumerable: true
, configurable: true
});
}
}
});
}
显然,我对 JS 的内部结构或一般的反射知之甚少.这是一种适用于标题的方法:
Obviously, I don't know much about the internals of JS or reflection in general. Here is a method that works for title:
var observer = new window.MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
change({title: mutation.target.textContent});
});
});
observer.observe(document.querySelector('head > title'),
{ subtree: true, characterData: true, childList: true });
但我无法通过查询选择器指定位置,而且我很确定它需要实现节点类才能让观察者工作.
But I can't specify Location via a query selector and I'm pretty sure it would need to implement the node class for observer to work.
推荐答案
在非 Firefox 浏览器中,您无法在 location.href
上设置观察者.我需要在 location.pathway
、location.hash
和 location.search
上设置观察者.
In non-Firefox browsers, you cannot set a watcher on location.href
. I needed to set the watcher on location.pathway
, location.hash
, and location.search
instead.
最好只重用一个函数,而不是将同一个函数写出两次.我能够把它剃成这样:
It is also better to just reuse a function instead of writing the same one out twice. I was able to shave it down to just this:
if (!Object.prototype.watch) { //don't overwrite gecko watch function
Object.prototype.watch = function(prop, handler) {
var oldval = this[prop], newval = oldval,
getter = function() {
return newval;
},
setter = function(val) {
oldval = newval;
return newval = handler.call(this, prop, oldval, val);
};
if (delete this[prop]) {
Object.defineProperty(this, prop, {
get: getter,
set: setter
});
}
};
}
这篇关于为 window.location 附加更改通知程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!