【问题标题】:Attaching change notifier for window.location为 window.location 附加更改通知器
【发布时间】:2014-03-03 00:27:51
【问题描述】:

每当 window.location.href 发生变化时,我都需要触发一个函数,但我遇到了问题。我查看了各种watch polyfills 的源代码,但我不能完全理解代码发生了什么。

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 的内部结构或一般反射知之甚少。这是一个适用于标题的方法:

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 });

但我不能通过查询选择器指定位置,我很确定它需要实现节点类才能让观察者工作。

【问题讨论】:

    标签: javascript reflection


    【解决方案1】:

    在非 Firefox 浏览器中,您无法在 location.href 上设置观察者。我需要将观察者设置为 location.pathway、location.hash 和 location.search。

    最好只重用一个函数,而不是把同一个函数写两次。我能够把它剃成这样:

    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
          });
        }
      };
    }
    

    【讨论】:

    • 这对你有用吗?我无法在 location.pathname 上定义设置器
    • 我不记得了,就像...一样。 :p
    【解决方案2】:

    这有点小题大做,但并不比我见过的任何其他东西多多少,它在所有现代浏览器中的工作原理几乎相同。

    var myTitle = document.title;
    var myLocation = window.location.href;
    
    setInterval(function() {
        if (myTitle != document.title || myLocation != window.location.href)
        {
            // Do something here;
    
            myTitle = document.title;
            myLocation = window.location.href;         
        }
    }, 100);
    

    它只是在短时间内轮询属性。简而言之,对用户可见,但它也不应该有太多的 CPU 开销。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-27
      • 1970-01-01
      • 2011-08-18
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多