我正在观察一个对象,并希望在更改值时调用一个函数。在代理对象(Javascript ECMAscript)中调用外部函数
我可以用Object.observe做到这一点,并希望尝试使用Proxy进行简化。
我无法调用外部函数,导致它说未定义。 如何捕捉外部功能?
这里是我的事:
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
}
编辑为跟进回答
功能doStmg()被调用,并在其中执行//Stuff
,除了externalFunction
仍然是未定义。 externalFunction
通常在别处被调用。
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
}
代理有一个 '处理' 和 '目标' 是不同的。你的代理目标是'页面'和处理'pageHandler'你的目标不包含externalFunction所以它是未定义的。你应该将外部函数移动到页面作为属性 –
它适用于我在任何情况下 – MinusFour
谢谢大家。 @ftor @Shyam Babu你能举个例子吗?我尝试了const'page = {externalFunction:externalFunction}',然后在'doSmtg()'中调用它作为'page.externalFunction'或'target.externalFunction',但没有奏效。 – user305883