在代理对象中调用外部函数(Javascript ECMAscript)

hmmo2u0o  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(497)

我正在观察一个对象,并希望在更改值时调用一个函数。
我可以用Object.observe来做,并想尝试用Proxy来简化。
我不能调用外部函数,因为它说undefined。如何捕获外部函数?
我的想法是

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,除了仍然未定义的externalFunctionexternalFunction通常在其他地方调用。

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
}
ve7v8dk2

ve7v8dk21#

至于OP给出的例子...不仅页面处理程序选项的配置必须改变,该选项只应针对指定的陷阱,而且还应注意,对于上面的示例,必须使用proxyPage对象才能运行到set陷阱。将值直接分配给任何page属性,否则将不会被检测到。

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

相关问题