0

我正在尝试查看是否有一种方法可以自动将start, stop,before:start事件绑定到所有已初始化的模块,而无需this.on('start',function() {})向每个模块添加样板。

我只是通过这些函数进行一些基本的日志记录/调试,以帮助我更好地了解我的基础架构,如果我可以定义类似于如何覆盖原型被覆盖的事件,那就太酷了。

为了完成这样一个看似简单的任务,我必须添加“样板”类型的示例。显然这是在咖啡里......

@on "before:start", ->
  console.log "starting: #{Self.moduleName}"
  return
@on "start", (defaults)->
  _init()
  console.log "started: #{Self.moduleName}"
  return
@on "stop", () ->
  console.log "stopped: #{Self.moduleName}"
  return

  _init = () ->
    return

我的第一个想法是以MyApp.module()某种方式覆盖该函数并将事件绑定放在那里?不知道我会怎么做... :-/

如何做到这一点?

4

1 回答 1

1

我会照你说的做。
您可以覆盖构造函数。但是如果你这样做,你必须非常小心,并重新绑定任何静态方法和绑定到它的原型。基本上,你可以这样做:

var module = Marionette.Module;
Marionette.Module = function() {
  // this would be bound BEFORE anything else happens
  this.on('before:start', ...);

  module.apply(this, arguments);

  // this would be bound AFTER anything else happens
  this.on('before:start', ...);
};

再说一次,你必须在之后重新绑定原型和静态方法。

编辑:
关于重新绑定:

// save the prototype and any static method (or value)
var protoProps = Marionette.Module.prototype;
// this is maybe only the extend function
var staticProps = {};
for(var prop in Marionette.Module) staticProps[prop] = Marionette.Module[prop];

// override the Module
var module = Marionette.Module;
Marionette.Module = function() {
  ...
};

// rebind
Marionette.Module.prototype = protoProps;
_.extend(Marionette.Module, staticProps);
于 2013-04-08T14:59:36.940 回答