Question

  

Possible en double:    Javascript Object.Watch pour tous les navigateurs?

Je viens de lire la documentation de Mozilla pour le méthode watch () . Il semble très utile.

Cependant, je ne peux pas trouver quelque chose de similaire pour Safari. Ni Internet Explorer.

Comment gérez-vous la portabilité entre les différents navigateurs?

Était-ce utile?

La solution

J'ai créé un petit object.watch shim pour cela il y a un certain temps. Il fonctionne dans IE8, Safari, Chrome, Firefox, Opera, etc.

/*
* object.watch v0.0.1: Cross-browser object.watch
*
* By Elijah Grey, http://eligrey.com
*
* A shim that partially implements object.watch and object.unwatch
* in browsers that have accessor support.
*
* Public Domain.
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/

// object.watch
if (!Object.prototype.watch)
    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]) { // can't watch constants
            if (Object.defineProperty) // ECMAScript 5
                Object.defineProperty(this, prop, {
                    get: getter,
                    set: setter
                });
            else if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { // legacy
                Object.prototype.__defineGetter__.call(this, prop, getter);
                Object.prototype.__defineSetter__.call(this, prop, setter);
            }
        }
    };

// object.unwatch
if (!Object.prototype.unwatch)
    Object.prototype.unwatch = function (prop) {
        var val = this[prop];
        delete this[prop]; // remove accessors
        this[prop] = val;
    };

Autres conseils

Malheureusement, ce n'est pas une solution portable. IE n'a rien comme ça à ma connaissance, bien que ce serait génial s'il y avait

Vous pouvez probablement mettre en œuvre votre propre système de notifcation, en réécrivant les méthodes et les variables. Je ne le vois pas comme étant critique que si, mais je ne sais pas ce que vous envisagez de faire avec un tel système.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top