Reputation: 28309
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?
Upvotes: 0
Views: 1040
Reputation: 114792
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 style
binding rather than the attr
binding, 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-position
is 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 JavaScript backgroundPosition
you would either want your getValue
function to return the full string like 15px 30px
or build it in the binding like: getValue($index) + ' ' + getValue($index)
$index
is 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:
<i class="icon-blah" data-bind="style: { backgroundPosition: viewModel.getValue($index) + ' ' + viewModel.getValue($index) }"></i>
Sample here: http://jsfiddle.net/rniemeyer/BAVZa/
Upvotes: 2