I am wondering if it is possible with knockoutjs to pass arguments when binding.
I am binding a list of checkboxes and would like to bind to a single computed observable in my viewmodel. In my viewmodel (based on parameter passed to the read function) I want to return true/false based on certain conditions.
var myViewModel=function(){
this.myprop=ko.computed({read: function(){
//would like to receive an argument here to do my logic and return based on argument.
}
});
};
<input type="checkbox" data-bind="checked: myprop(someval1)" />
<input type="checkbox" data-bind="checked: myprop(someval2)" />
<input type="checkbox" data-bind="checked: myprop(someval3)" />
Any suggestions?
Create a function whose sole purpose is to return a computed observable. It may take in parameters as you wanted. It will have to be a separate computed observable if you want it to be a two-way binding.
Then in your binding, call that function with the appropriate arguments. The computed observable it returns will be bound to in your view and will update as usual.
Here's a fiddle where I used this technique for creating event handlers. You can do something similar here.
You can keep it clean by making the function a method on the observable. Either by adding to the
ko.observable.fn
prototype or adding it directly to the observable instance.Then apply to your view
Demo
However if you are just trying to bind all those checkboxes to a single value in your view model, you don't need to do that. Use the
checked
binding on an array in your view model and give your checkboxes a value. Every checked value will be added to the array. And it will be a two way binding.Demo
Without knowing the specifics, it seems like what you should be doing is defining a ko.observableArray or computed array value
HTML:
JS:
and not passing values from the markup to define the model state
The accepted answer is decent, but if you have a function that generates a ko.computed for each checkbox, you are adding unnecessary overhead with multiple anonymous computed observables, which adds up quickly when your checkbox lists exceed 4-5 options.
This is a simpler implementation of a bitwise scenario, but the computed function can be whatever need be.
Script:
Example fiddle here: http://jsfiddle.net/i_vargas3/RYQgg/
There is no reason to use a
computed
value. Simply define a function in your View Model and bind thechecked
to it.Below is a very simplistic example.
--
HTML
JS
--
That being said it is a good idea to try and push as much of the logic into your View Model as is possible. It would be advisable to create a View Model that models your checkbox as an object, and then the logic as to if the checkbox should be checked could be encapsulated inside.
--
EDIT: Based on the requirement to do two-way binding I have written an extender to manage an observable.
http://jsfiddle.net/jearles/j6zLW/5/