1
我得到一個RequireJs模塊,該模塊實例化另一個模塊並代理它的一些方法。我現在想隱藏模塊實例本身,只允許通過代理方法進行訪問。私有對象屬性
define(['mediator'], function(Mediator) {
var Proxy;
Proxy = function(prefix) {
this.prefix = prefix;
this.mediator = new Mediator();
};
Proxy.prototype.on = function(event, callback, context) {
this.mediator.subscribe(this.prefix + event, callback, context || this);
};
Proxy.prototype.off = function(event, callback, context) {
this.mediator.unsubscribe(this.prefix + event, callback, context || this);
};
Proxy.prototype.trigger = function() {
arguments[0] = this.prefix + arguments[0];
this.mediator.trigger.apply(this.mediator, arguments);
};
return Proxy;
});
require(['proxy'], function(Proxy) {
var proxy = new Proxy('sample:');
// this access is secured and bound to the prefix
// I cannot mess up with other events which do not belong to me
proxy.on('log', function(message) { console.log(message); });
proxy.trigger('log', 'hi hello');
// unfortunately there still would be a hack to leave my event scope
proxy.mediator.trigger('outerscope:test', 'blabla');
});
正如你看到的將有可能訪問代理原型和亂用它內部使用的調解對象...
現在我想以某種方式隱藏仲裁器實例,但有不知道在哪裏。 我可以將它存儲在requirejs模塊回調中的某個正常變量中,但這對requirejs不起作用,並可能導致重疊。
那我還能做什麼?
UPDATE:
define(['mediator'], function(Mediator) {
var Proxy;
var mediator = new Mediator();
Proxy = function(prefix) {
this.prefix = prefix;
};
Proxy.prototype.on = function(event, callback, context) {
mediator.subscribe(this.prefix + event, callback, context || this);
};
Proxy.prototype.off = function(event, callback, context) {
mediator.unsubscribe(this.prefix + event, callback, context || this);
};
Proxy.prototype.trigger = function() {
arguments[0] = this.prefix + arguments[0];
mediator.trigger.apply(this.mediator, arguments);
};
return Proxy;
});
require(['proxy'], function(Proxy) {
var proxy = new Proxy('sample:');
proxy.on('log', function(message) { console.log(message); });
});
你是什麼意思,說'這不適合requirejs,可能會導致重疊'?這是封裝Mediator實例的好方法。它可用於代理服務器,但不在外部。確切地說你需要什麼。 – dfsq
@dfsq你能寫一個答案,所以我可以標記? – bodokaiser