0

我试图看看是否有办法将start,stop,before:start事件自动绑定到所有已初始化的模块,而无需向每个模块添加this.on('start',function() {})样板。Backbone.js/Marionette.js全局模块事件绑定...?

我只是在做通过这些功能的一些基本的日志/调试帮助我理解我的基础好一点,这将是冷静,如果我可以定义类似于如何来推翻原型被覆盖的事件。

的“样板”的类型的实施例我在添加完成这样一个看似简单的任务。 显然,这是在咖啡...

@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()功能,并把事件绑定在那里?不知道我会怎么做,虽然...: -/

如何将一个做到这一点?

回答

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', ...); 
}; 

然后再次,你必须重新绑定原型和静态方法。

编辑:
关于rebindings:

// 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); 
+0

所以,你说这是一个可行的解决我的问题,或者我应该试试别的? 后'module.apply' 然后我可以做一些像_.extend(这个,模块) – 2013-04-08 15:24:15

+1

你可以做任何你想做的事情,只要确保你不干扰Backbone(或Marionette's)的内部东西。但只要你做正确的事(见我的约rebindings评论),这不能伤害(尤其是如果你只使用这个作为开发工具)。 – Loamhoof 2013-04-08 15:26:21

+0

谢谢,这是非常有用的,我已经得到它的工作。 – 2013-04-08 15:47:40