我正在觀察一個對象,並希望在更改值時調用一個函數。在代理對象(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