从 ractive on-click 调用多个函数

Calling multiple functions from a ractive on-click

是否可以通过单击事件触发两个反应函数。我假设它会尝试通过使用分号来表现与 onclick 相同的行为,但它不会触发任何一个功能。

模板:

<div on-click="hello; world;"></div>

JS:

Ractive.on('hello', function(){
    console.log('hello');
});

Ractive.on('world', function(){
    console.log('world');
});

我试过逗号分隔和 space 分隔。从一个单击事件中触发这两个函数的正确方法是什么。

您只能触发一个代理事件:

http://docs.ractivejs.org/latest/proxy-events

但也许你可以这样做:

<div on-click="hello" ></div>
<div on-click="world" ></div>
<div on-click="helloWorld" ></div>

function hello(){
    console.log('hello');
}

function world(){
    console.log('world');

}
Ractive.on('hello', function(){
    hello();
});

Ractive.on('world', function(){
   world();
});

Ractive.on('helloWorld', function(){

  hello(); world();
});

这是一个类似于下面@Juan 的人为示例,但您可以有一个自定义事件来触发其他两个。

模板

<div on-click="custom"></div>

JS

Ractive.on('custom', function() {
  Ractive.fire('hello');
  Ractive.fire('world');
});

Ractive.on('hello', function(){
  console.log('hello');
});

Ractive.on('world', function(){
  console.log('world');
});

Brett 的回答很好 - 在大多数情况下,我都推荐这样做。如果你想在很多情况下这样做,你可以像这样抽象出来:

Ractive.prototype.fireEvents = function () {
  var len = arguments.length;
  for ( var i = 0; i < len; i += 1 ) {
    this.fire( arguments[i], this.event );
  }
};

var ractive = new Ractive({
  el: 'main',
  template: '#template'
});

ractive.on({
  foo: function () {
    alert( 'fired foo' );
  },
  bar: function () {
    alert( 'fired bar' );
  },
  baz: function () {
    alert( 'fired baz' );
  }
});
<script src='http://cdn.ractivejs.org/latest/ractive.js'></script>

<main></main>

<script id='template' type='text/html'>
  <button on-click='fireEvents("foo","bar","baz")'>fire events</button>
</script>

完全鼓励像这样修改原型以添加您需要的额外功能。