calling external function in Proxy object (Javascript ECMAscript)

234 Views Asked by At

I am observing an object and want to call a function upon changing values.

I could do it with Object.observe and would like to try simplify with Proxy.

I cannot call an external function, cause it say undefined. How to trap an external function ?

here's my thing:

const page = {}
const pageHandler = {
    externalFunction : externalFunction, // does not work: gets undefined
    doSmtg : function(value) { 
      // do something on a value
      externalFunction( value ) // externalFunction is undefined 
      this.externalFunction( value ) // same problem
    },  
    set( target, key, value) {

    if (key == 'article') {

         this.doSmtg( value );

      }
    }
}

const proxyPage = new Proxy( page , pageHandler);


function externalFunction( myObject) {

     // do things on my Object
     // this function can be called somewhere else then proxy Page

}

EDITED as follow up to answer

The function doStmg() is called and execute //Stuff in it, except for the externalFunction which still is undefined. externalFunction is called normally elsewhere.

const page = {
  // observePage : observePage
}

const pageHandler = {
  // observePage : observePage,
  set : setPageProperty,

  get(target, key) {
    console.log('Getting page', target[key]);
    return target[key]
  }
};

const proxyPage = new Proxy( page , pageHandler);


function setPageProperty(target, key, value) {
    target[key] = value;
     if (key == 'article') {
          doSmtg( value );
    }   
}


function doSmtg( article ) {

        // stuff

        $("a[href*='/url/']").click(function(e){

            param = {
                titles : l
            };

            externalFunction(param, pageCallback, setOpenFromGraph(false));

        });

  }


function externalFunction(param, firstCallback, secondCallback) {
    //  stuff
}
1

There are 1 best solutions below

1
On

As for the OP's given example ... not only the configuration of the page handler options which only should target specified traps has to be changed, but one also should be aware that with the example from above one has to work with the proxyPage object in order to run into the set trap. Assigning a value directly to any page property otherwise will not be detected.

function externallyHandlePageArticleChange(value) {
  console.log("externallyHandlePageArticleChange :: value :", value);
}


function handlePagePropertyChange(target, key, value/*, receiver*/) {
  console.log("handlePagePropertyChange :: [target, key, value] :", target, key, value);

  target[key] = value;

  if (key === 'article') {

    externallyHandlePageArticleChange(value);
  }
  return true;
}

var pageHandlerOptions = {
  set: handlePagePropertyChange
};

var page = new Proxy({}, pageHandlerOptions);


page.x = "x";
page.y = "y";
page.article = "0815";
.as-console-wrapper { max-height: 100%!important; top: 0; }