Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I find when window.onclick() function overridden?

in javascript, is it possible to make an event handler when a function attribute changes from

window.onclick = function() {  ....function 1...... };

to

window.onclick = function() {  ....function 2..... };
like image 927
Mohan Kumar Avatar asked May 26 '15 13:05

Mohan Kumar


People also ask

Does Onclick only work once?

Unfortunately when the user clicks on the event a quotes does show up, but it only works once. If the user tries to click the div again it doesn't work.

What is window onclick in JavaScript?

The onclick event occurs when the user clicks on an element. In HTML: <element onclick="myScript"> In JavaScript: object.


1 Answers

This is a few years old, but it has worked great for me. An SO user posted an open-source object watcher a few years back. It modifies the object prototype so that you watch for changes to specific properties of the object.

window.watch('onclick', function() { console.log('changed'); });
window.onclick = function() {  console.log('click1'); };
window.onclick = function() {  console.log('click2'); };

JSFiddle: https://jsfiddle.net/gou48xpa/

Source code: https://gist.github.com/eligrey/384583 (released with MIT license)

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

// object.unwatch
if (!Object.prototype.unwatch) {
    Object.defineProperty(Object.prototype, "unwatch", {
          enumerable: false
        , configurable: true
        , writable: false
        , value: function (prop) {
            var val = this[prop];
            delete this[prop]; // remove accessors
            this[prop] = val;
        }
    });
}
like image 187
Jason W Avatar answered Oct 10 '22 12:10

Jason W