For example i have such template and i want to calculate some values dynamically based on current $index
<div class="cond" title="Click to flip">
<div class="condFlip" data-bind="attr: {id: Id }, click: viewModel.setClick">
<div class="piece-all piece" data-bind="attr: {style: background-position: viewModel.getValue($index) viewModel.getValue($index) }"></div>
</div>
</div>
</script>
<script type="text/javascript">
viewModel = {
flips: ko.observableArray([]),
setClick: function (data, e) {
e.preventDefault();
//doing things
},
getValue: function (data, e) {
return //get my value
}
};
ko.applyBindings(viewModel);
so how can i use function viewModel.getValue in model binding? is there any way of doing this?
You can call functions that return strings in the way that you are doing it, but your format is slightly off. Here are a few tips:
you can use the
stylebinding rather than theattrbinding, as it will add/remove the individual styling rather than replace the entire style attribute (maybe not important for your case).in the binding string,
background-positionis an invalid property name in the object literal that you are creating to specify your bindings. You need to either use"background-position"in quotes or the name that you can use in JavaScriptbackgroundPositionyou would either want your
getValuefunction to return the full string like15px 30pxor build it in the binding like:getValue($index) + ' ' + getValue($index)$indexis an observable, so you will need to call it as a function to get its value, when you are processing it in your function.So, your binding might look like:
Sample here: http://jsfiddle.net/rniemeyer/BAVZa/