2012-10-20 75 views
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); }); 

}); 
+0

你是什麼意思,說'這不適合requirejs,可能會導致重疊'?這是封裝Mediator實例的好方法。它可用於代理服務器,但不在外部。確切地說你需要什麼。 – dfsq

+0

@dfsq你能寫一個答案,所以我可以標記? – bodokaiser

回答

2

這是可變的封裝在Javascript封閉件內的典型的例子。你需要的是將你的中介實例定義爲與Proxy相同範圍內的局部變量。這將允許Proxy對象通過閉包訪問Mediator,但會將Mediator與define-callback外的代碼隔離。所以像這樣:

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; 

});