简体   繁体   English

修改在回调中传递的变量

[英]Modify variable passed in callback

How can i modified/update a variable passed inside a callback ? 如何修改/更新在回调内传递的变量?

Example: 例:

 function App() { this.components = {}; this.queue = {}; } App.prototype.import = function (name, cb) { if (this.components[name]) { return cb(this.components[name]); } if (!this.queue[name]) { this.queue[name] = []; } // push to queue this.queue[name].push(cb); }; App.prototype.export = function (name, data) { let that = this; // set components instance this.components[name] = data; // call queue ? if (this.queue[name]) { // call each import request this.queue[name].forEach(function (cb) { cb(that.components[name]); }); // clean up delete this.queue[name]; } }; App.prototype.reload = function (name, data) { console.log("Reload module %s", name); delete this.components[name]; this.components[name] = data; }; var app = new App(); app.import("module1", function(data){ console.log("Imported module1"); setInterval(function(){ console.log(data, app.components["module1"]); }, 1000); }); setTimeout(function(){ app.export("module1", {data: "Hello World"}) }, 1000); setTimeout(function(){ app.reload("module1", {data: "Changed data"}); }, 5000); 

If you run this snipet you can see: app.components.module1 is updated but not the callback scope. 如果运行此代码段,您将看到:app.components.module1已更新,但未回调范围。 How can i solve this ? 我该如何解决?

I want if the app.components.module1 is updated the variable in the cb too. 我想要app.components.module1也更新cb中的变量。

You cannot delete the object as you will loose reference. 您不能删除对象,因为您将丢失引用。 However you could mutate it: 但是,您可以更改它:

App.prototype.reload = function (name, data) {
  console.log("Reload module %s", name);
  Object.keys(this.components[name]).forEach(key =>{
    delete this.components[name][key];
  });
  Object.assign(this.components[name],data);
};

(That wont work with primitive types and isnt the best code design) (这不适用于原始类型,也不是最佳的代码设计)

Or you implement sth like a Listener pattern: 或者您像侦听器模式一样实现某事:

class Listener {
 constructor(){
    this.listeners = new Map();
  }
  on(event,handler){
    if( this.listeners.has(event) ){
      this.listeners.get(event).push(handler);
    }else{
      this.listeners.set(event,[handler]);
    }
  }

  trigger(event, ...params){
    (this.listeners.get(event) || []).forEach( handler => handler(...params));
  }
}

So one can do: 所以可以做到:

const loader = new Listener();
loader.on("sth",console.log);

loader.trigger("sth",{a:1});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM