Reputation: 77
I am trying to do some like this. is it a valid syntax? I am checking for some flag value and toggling b/w two css classes?
<div data-bind="visible:'anchorJobContractor'===JobDetail_SelctedTab(), css:IsTabsCollapsed ? TabCollapsed : TabExpanded"></div>
First part visible dataBinding works for me.
Upvotes: 2
Views: 5545
Reputation: 145880
Disclaimer: Quick and dirty version
I needed a quick and dirty way to apply a class to a debugging panel, and came up with the following.
I recommend this version only for debugging, and it only works if you are also using jQuery.
<div class="debug-only knockout-debug-panel"
data-bind="click: function(data, event) { $(event.currentTarget).toggleClass('transparent'); }">
</div>
.transparent { opacity: .5; }
Knockout has a function toggleDomNodeCssClass
, but unfortuntely it requires a boolean whether to add or remove the class.
Upvotes: 0
Reputation: 3529
This is one possible syntax for css binding:
<div data-bind="css: { TabCollapsed: IsTabsCollapsed, TabExpanded: !IsTabsCollapsed() }"></div>
See also documentation at: http://knockoutjs.com/documentation/css-binding.html
Upvotes: 4
Reputation: 14094
You can use the CSS binding with a computed observable like this.
<div data-bind="css: TabClass">
...
</div>
<script type="text/javascript">
var viewModel = {
IsTabsCollapsed: ko.observable(false);
};
viewModel.TabClass = ko.computed(function() {
return this.IsTabsCollapsed() ? "TabCollapsed " : "TabExpanded";
}, viewModel);
</script>
It's not the smallest and cleanest way to achieve what you want, but it's really easy to manage and alter, and very understandable.
Upvotes: 0
Reputation: 1746
If IsTabsCollapsed is an observable you have to do:
IsTabsCollapsed() ? TabCollapsed : TabExpanded
Upvotes: 0
Reputation: 5053
Can you try encasing the logic for CSS within braces like this:
<div data-bind="visible:'anchorJobContractor'===JobDetail_SelctedTab(), css: { IsTabsCollapsed ? TabCollapsed : TabExpanded }"></div>
Either that or you could move the logic into your javascript rather than doing it in the HTML by using a computed value.
viewModel.myCssClass = ko.computed(function() {
return IsTabsCollapsed ? "TabCollapsed" : "TabExpanded";
}, viewModel);
<div data-bind="visible:'anchorJobContractor'===JobDetail_SelctedTab(), css: myCssClass"></div>
Upvotes: 1