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 并且可能导致重叠。

那我还能做什么?

更新:

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

});
4

1 回答 1

2

这是 Javascript 中闭包内变量封装的典型示例。您需要将调解器实例定义为与Proxy. 这将允许 Proxy 对象通过闭包进行访问,Mediator但会将 Mediator 与您的定义回调之外的代码隔离开来。所以像这样:

define(['mediator'], function(Mediator) {

    // Make mediator local scope variable
    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);
    };

    // ... rest of the code

    return Proxy;

});
于 2012-10-20T09:00:35.103 回答