Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind a css class name to a viewmodel with knockoutjs

Tags:

knockout.js

I am doing this css binding:

css: { greenBorder: hasGreenBorder, whiteBorder: hasWhiteBorder, blackBorder: hasBlackBorder }

This works but why should my viewmodel return not just the css class name like .whiteBorder or .blackBorder.

because my logic is that from all 3 has-Variables there can only be one true the others are always false.

I think there must be a better way just to apply the class name and put this logic which classname to choose in my viewmodel, right?

like image 820
bastienne Avatar asked Jul 19 '13 07:07

bastienne


2 Answers

You can use the attr binding.

data-bind="attr: { class: yourClass }"
like image 75
david.s Avatar answered Sep 19 '22 18:09

david.s


The proper way

The class binding is what you are looking for.

This binding allows you set an arbitrary css class for an element. It requires jQuery.

Usage :

<div data-bind="class: single">Single Observable Class</div>
<div data-bind="class: multiple">Multiple Observable Classes</div>



var vm = {
    single: ko.observable("red"),
    multiple: ko.observableArray(["blue","small"])
};
vm.change = function () {
    vm.single(vm.single() === "red" ? "black" : "red");

    if (vm.multiple.indexOf("small") > -1) {
        vm.multiple.remove("small");
        vm.multiple.push("big");
    } else {
        vm.multiple.remove("big");
        vm.multiple.push("small");
    }    
};

I hope it helps

like image 32
Damien Avatar answered Sep 19 '22 18:09

Damien