Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs - multiple bindings on click event

I would like to know if it is possible to create multiple bindings on an event in knockout.js

example:

<span data-bind="click: function1 function2, attr: {}"></span> 
like image 909
Safari Avatar asked Mar 18 '12 19:03

Safari


2 Answers

Try to use

<span data-bind="click: function() { function1(); function2() }"></span> 
like image 80
Vladimir Posvistelik Avatar answered Sep 19 '22 16:09

Vladimir Posvistelik


EDIT: I accidentally used the MooTools typeOf() without thinking. Fixed.


Here's what I came up with. I admit it's overkill for most situations but the syntax is a bit cleaner on the template side:

View Model:

var ViewModel = new function() {     this.call = function(functions,args) {         if (!(functions instanceof Array))             functions = [functions];         if (!(args instanceof Array))             args = [args];          return function() {             for (var i = 0, l = functions.length; i < l; i++) {                 functions[i].apply(this,args);             }         }     }      this.testValue=ko.observable('Click me!');     this.click1 = function(foo) {         this.testValue('click1 ' + foo);         alert(1);     }     this.click2 = function(foo) {         this.testValue('click2 ' + foo);         alert(2);     } } 

and template

<span data-bind="click:call([click1,click2],['Test value'])">Test span</span> 
like image 25
jpeltoniemi Avatar answered Sep 17 '22 16:09

jpeltoniemi