0
콜백 내부에서 전달 된 변수를 수정/업데이트 할 수 있습니까?콜백에서 전달 된 변수 수정
예 :이 snipet을 실행하면
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);
당신이 볼 수 app.components.module1 업데이트하지만 콜백 범위입니다. 어떻게 해결할 수 있습니까?
app.components.module1이 cb의 변수도 업데이트하고 싶습니다.
이것은 이벤트 이미 터와 비슷합니다. 그게 내가 원하는 건 아니에요. 리스너를 다시 호출하지 않고 콜백 인수 객체를 변경합니다. – Marc