【发布时间】:2012-10-20 07:23:57
【问题描述】:
我有一个 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 并且可能导致重叠。
那我还能做什么呢?
更新:
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); });
});
【问题讨论】:
-
this would not work good with requirejs and could cause overlapping是什么意思?这是封装 Mediator 实例的好方法。它可用于代理,但不可用于外部。正是您需要的。 -
@dfsq 你能写一个答案让我标记吗?
标签: javascript object prototype requirejs private