我已经阅读了Ractive文档并且我有点头疼,因为看起来默认事件初始化选项允许我做某事 - 创建新事件类型 - 更多比我需要的更复杂,但相反,对于更简单的(更常见的)定义默认事件
的任务没有任何钩子有人可以提供有关如何提供可能针对传统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.events
和Ractive.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>
这样的东西会起作用吗?这对我来说似乎很奇怪。我理解概念修正吗?如果没有,我错过了什么?
有没有一种简单的方法来实现第一个例子?
答案 0 :(得分:2)
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
});
}
请注意,必须在您同时实施this._super();
的任何组件中调用oninit
:
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...
}
}