如何在 Ractive initialization/defaults 中包含事件(不是事件插件)?

How to Include events (not event-plugin) in Ractive initialization/defaults?

我已经通读了 Ractive 文档,但有点摸不着头脑,因为默认事件初始化选项似乎允许我做一些事情——创建新事件types - 比我需要的要复杂得多,但相反,对于定义默认 events

的更简单(更常见?)的任务没有任何帮助

有人可以建议如何提供可以为传统 DOM 事件触发的全局事件吗?

示例:

我有一个 3 组件应用程序页面。我想定义一个 getOptions 事件,这样任何 <select on-click='getOptions'>...</select> 都将由同一个函数处理。我不想在每个组件中都定义该函数。

我的直觉是做以下事情:

Ractive.events['getOptions'] = function(event){
   //logic for getting the options for the value in event.keypath
}

或者,如果我想要一个可以被覆盖的真正默认值...

Ractive.default.events['getOptions'] = function(event){
   //logic for getting the options for the value in event.keypath
}

但是 我对文档的理解是 Ractive.eventsRactive.default.events 提供这个,而是提供一种定义新事件插件的方法,它依赖于一个单独的触发机制:

Ractive.events.getoptions = function(node,fire){
   //here goes logic for interacting with DOM event listeners, etc
}
//and then i would need to do this
ractive = Ractive.extend({...});
ractive.on('someOtherEventName',function(event){
   //logic for getting the options for the value in event.keypath
});

//and then I could do this...
<select on-getoptions='someOtherEventName'>...</select>

但是在这种情况下,会触发 getoptions - 来自模板,而不是 js ractive.fire()?

<select on-getoptions='someOtherFunction' on-click=getoptions>...</select> 这样的东西行得通吗?这对我来说似乎很奇怪。我理解概念修正吗?如果没有,我错过了什么?

有没有简单的方法可以实现第一个例子?

Ractive.events 指的是在 dom 和模板之间进行调解的自定义事件:

Ractive.events.banana = function( node, fire ) { ... };

<div on-banana="doSomething()"/>

事件的处理程序可以是要触发的事件的名称,也可以是组件实例上的方法。

在你的情况下,我认为在 Ractive.prototype 上定义一个方法是拥有一个通用处理程序的最佳方式:

Ractive.prototype.getOptions = function( /* pass in arguments */ ){
    // and/or this.event will give you access 
    // to current event and thus context

    // you can also override this method in components and 
    // call this base method using this._super(..)
}

// now any ractive instance can use:
<select on-click="getOptions(data)">...</select>

基于事件的方法通常需要让视图层次结构中的根实例或公共父级跨子组件处理同一事件:

var app = new Ractive({
    template: "<componentA/><componentB/>",
    oninit(){

        this.on( '*.getOptions', ( event, arg ) => {
            // any child component (at any depth)
            // that fires a "getOptions" event will
            // end up here
        });
    }
});

// in component A or B:
<select on-click="getOptions">...</select>

UPDATE:如果你想为原型分配一个事件处理程序,那么本质上每个组件都预先连接以处理一个设置名称的事件,你可以这样做:

Ractive.prototype.oninit = function(){
    this.on( 'getOptions', ( event ) => {
        // handle any "getOptions" event that happens in the instance
    });
}

请注意,您 必须 在您还实现了 oninit:

的任何组件中调用 this._super();
var Component = Ractive.extend({
    oninit() {
        // make sure we call the base or event listener won't happen!
        this._super();

        // do this component instances init work...
    }

}