Maison  >  Article  >  interface Web  >  Puis-je toujours surveiller les modifications d’objets dans les navigateurs après que Object.watch() soit obsolète ?

Puis-je toujours surveiller les modifications d’objets dans les navigateurs après que Object.watch() soit obsolète ?

DDD
DDDoriginal
2024-10-28 22:04:30996parcourir

 Can I Still Monitor Object Changes Across Browsers After Object.watch() Was Deprecated?

Surveillance des modifications d'objets multi-navigateurs avec Object.watch()

Question : Existe-t-il un moyen de surveiller l'objet change de manière cohérente sur plusieurs navigateurs, malgré la dépréciation d'Object.watch() ?

Réponse de 'pseudoecstatic' :

Oui, j'ai développé un simple Object.watch () qui fonctionne de manière transparente sur IE8, Safari, Chrome, Firefox, Opera et d'autres navigateurs populaires.

Mise en œuvre :

Incluez la cale suivante dans votre projet :

<code class="javascript">(function () {
  var toString = Object.prototype.toString,
    isNative = function (obj) {
      return toString.call(obj) === '[object Object]';
    },
    attachListener = function (target, prop, fn) {
      target.__watchers__ || (target.__watchers__ = {});
      target.__watchers__[prop] || (target.__watchers__[prop] = []);
      target.__watchers__[prop].push(fn);
    },
    detachListener = function (target, prop, fn) {
      if (target.__watchers__ && target.__watchers__[prop]) {
        var watchers = target.__watchers__[prop];
        for (var i = 0; i < watchers.length; i++) {
          if (watchers[i] === fn) {
            watchers.splice(i, 1);
            if (watchers.length === 0) {
              delete target.__watchers__[prop];
            }
            break;
          }
        }
      }
    },
    getWatchers = function (target, prop) {
      if (target.__watchers__ && target.__watchers__[prop]) {
        return target.__watchers__[prop];
      }
      return [];
    },
    notifyWatchers = function (target, prop, oldValue, newValue) {
      var watchers = getWatchers(target, prop);
      for (var i = 0; i < watchers.length; i++) {
        try {
          var newval = watchers[i](prop, oldValue, newValue);
          if (isNative(newval)) {
            newValue = newval;
          }
        } catch (e) {
          setTimeout(function () {
            throw e;
          }, 0);
        }
      }
      return newValue;
    },
    convert = function (prop, fn, target, rec) {
      var orig = target[prop];
      Object.defineProperty(target, prop, {
        configurable: true,
        enumerable: true,
        get: function () {
          return orig;
        },
        set: function (value) {
          if (orig !== value) {
            var oldval = orig;
            orig = notifyWatchers(target, prop, orig, value);
            fn(prop, oldval, orig, target);
          }
        }
      });
      if (rec && isNative(orig)) {
        for (var subprop in orig) {
          convert(subprop, fn, orig, rec);
        }
      }
    },
    watch = function (target, prop, fn, rec) {
      if (!target || typeof prop !== 'string' || typeof fn !== 'function') {
        throw new Error('Bad arguments');
      }
      attachListener(target, prop, fn);
      fn(prop, target[prop], target[prop], target);
      if (rec && isNative(target[prop])) {
        for (var p in target[prop]) {
          convert(p, fn, target[prop], true);
        }
      }
    },
    unwatch = function (target, prop, fn) {
      if (!target || typeof prop !== 'string') {
        throw new Error('Bad arguments');
      }
      detachListener(target, prop, fn);
    },
    constrained = function (val, defval) {
      if (val !== null && val !== undefined) {
        return val;
      } else {
        return defval;
      }
    },
    watchEvery = function (obj, fn, rec) {
      rec = constrained(rec, false);
      for (var p in obj) {
        convert(p, fn, obj, rec);
      }
    },
    stopWatchingEvery = function (obj, fn) {
      for (var p in obj) {
        unwatch(obj, p, fn);
        delete obj.__watchers__[p];
      }
    };
  Object.watch = watch;
  Object.unwatch = unwatch;
  Object.watchEvery = watchEvery;
  Object.stopWatchingEvery = stopWatchingEvery;
})();</code>

Utilisation :

Vous pouvez maintenant utiliser la cale Object.watch() comme suit :

<code class="javascript">var options = {'status': 'no status'},
watcher = Object.watch(options, 'status', function (prop, oldValue, newValue) {
  // Do something with the change...
});

watcher.status = 'asdf';
watcher.status = '1234';</code>

Cross -Compatibilité des navigateurs :

Cette cale garantit que la fonctionnalité Object.watch() est cohérente dans tous les principaux navigateurs, y compris ceux qui ne la prennent pas en charge nativement.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn