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
}
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 theset
trap. Assigning a value directly to anypage
property otherwise will not be detected.