Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
Knockout JS - bind css class to an element

I want to achieve dynamic class biding, which should assign and reassign correct class based on variable, putted in this field. The issue I got, when I induce function setRed(), and then setWhite(), both color classes are binded, and of course 1st CSS class is considered.

I've got an element which binding looks like that:

<div data-bind='dxNumberBox: dxCustomCalc'></div>

So far I made elementAttr class ko.observable();

self.dxCustomCalc = {
    displayExpr: 'Name',
    keyExpr: 'Id',
    value: self.customCalc,
    //onValueChanged: function (e) {
    //    self.childFormName(e.component.option('selectedItem'));
    //},
    disabled: ko.computed(function () {
        return self.readOnly;
    }),
    elementAttr: {
        /*   class: "is-valid-nok"*/        /* - red*/
        /*class: "is-valid-onlyok"  */    /* -white */
        /*class: "is-required-empty",*/  /* - yellow */
        class: ko.observable(),
    }
};

And went through element:

function setRed() {
    self.dxCustomCalc.elementAttr.class("is-valid-nok");
    console.log("color changed to red")
}

function setWhite(){
    self.dxCustomCalc.elementAttr.class("is-valid-onlyok");
    console.log("color changed to white")
}

Functions are executed based on value in field. For example, If value matches, function setRed() is fired. Then, if the value changes and the condition is met, function setWhite() is fired. The result I got, after executing both functions on subscription to element is:

<div data-bind="dxNumberBox: dxCustomCalc" class="dx-numberbox is-valid-nok is-valid-onlyok">

The result I want to achieve, after executing both functions is:

<div data-bind="dxNumberBox: dxCustomCalc" class="dx-numberbox is-valid-onlyok">
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I'd use the class binding to set a CSS class based on an observable.

You could do use it directly

<div data-bind="dxNumberBox: dxCustomCalc, class: dxCustomCalc.cssClass">

or you could apply the class binding as part of your dxCustomCalc custom binding, using ko.applyBindingsToNode():

ko.bindingHandlers.dxNumberBox = {
  init: function(elem, valueAccessor, allBindings, viewModel) {
    const value = ko.unwrap(valueAccessor());
    ko.applyBindingsToNode(elem, {class: value.cssClass}, viewModel);
  }
};

function DxNumberBox() {
  this.dxCustomCalc = {
    cssClass: ko.observable("is-required-empty")
  };
  this.setRed = () => this.dxCustomCalc.cssClass("is-valid-nok");
  this.setWhite = () => this.dxCustomCalc.cssClass("is-valid-onlyok");
  this.setEmpty = () => this.dxCustomCalc.cssClass("is-required-empty");
}

const vm = new DxNumberBox();
ko.applyBindings(vm);
.is-valid-nok {
  background-color: red;
}

.is-valid-onlyok {
  background-color: white;
}

.is-required-empty {
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-latest.js"></script>

<button data-bind="click: setRed">Red</button>
<button data-bind="click: setWhite">White</button>
<button data-bind="click: setEmpty">Empty</button>

<div data-bind="dxNumberBox: dxCustomCalc">
  Profit Information
</div>

<hr>
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>

Functions are executed based on value in field.

Having extra methods like .setRed() is clunky and unnecessary. Turn cssClass into a computed observable that calculates a class name based on the state of the viewmodel, e.g.

cssClass: ko.pureComputed(() => {
  var value = self.value().trim();
  if (value == '') return 'is-required-empty';
  if (value < 0) return 'is-valid-nok';
  return 'is-valid-onlyok';
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda