简体   繁体   中英

Calling multiple functions from a ractive on-click

Is it possible to fire two ractive functions with an on-click event. I assumed it would try to behave the same way the onclick does by using semi colons but it doesn't fire either function.

Template:

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

JS:

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

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

I've tried comma separated and space separated. What would be the correct way to get both of these functions to fire from one on-click event.

This is a contrived example similar to @Juan's below, but you could have a custom event that fires the other two.

Template

<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's answer is a good one - for most situations, I'd recommend that. If you wanted to do this in many situations, you could abstract it out like so:

 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> 

Modifying the prototype like this to add extra functionality you need is totally encouraged.

You can fire only one proxy event:

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

But maybe you can do:

<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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM