0

I want to set the css property using if condition using a normal variable other than observables. Like:

a.html file:

<span class="label" data-bind="text: isApproved, css: sampleglobalvar == true ? 'label-success' : 'label-important'"></span>

a.js file:

Edit:

define('durandal/app'],function(app) {
   var a = function() {

    sampleglobalvar = 'true'
    };
}

I am getting an error such as 'sampleglobalvar' doesnt exist in viewmodel . I know that a observable has to be used , but I have other problems with observable where switching between 'true' and 'false' for observables was creating problems:

Like if I use:

sampleglobalvar = ko.observable("");

setting :

if(//condition)
{

sampleglobalvar(true);
}
else
{
sampleglobalvar(false);
}

was not clearing the observable properly , due to which I am getting different results.

To summarize is it possible to use a normal javascript variable to use it in css data-bind property?

1
  • You put the 'sampleglobalvalue' in an annonymus function, making it a NON global.... Commented Jul 19, 2016 at 11:02

1 Answer 1

1

Yes, it's perfectly possible. For true global (i.e. stuff on window) you need to scope the variable in your databinding though.

Example:

function RootViewModel() {  
  // Plain property on the "global" (i.e. Root) view model:
  this.plainProp = true;
  
  // True "global" variable:
  window.myGlobal = true;
}

ko.applyBindings(new RootViewModel());
.error { background: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>

<p data-bind="css: plainProp === true ? 'error' : 'plain'">Root plain prop</p>
<p data-bind="css: window.myGlobal === true ? 'error' : 'plain'">Global plain prop</p>

You've included function scopes and a module loader (requirejs?) in the mix in your question, but as long as you get the scopings right for that exact scenario it should work analogous to my example. If you have a problem with that particular bit, I suggest asking another question, including a Minimal Repro (i.e. more (and syntactically valid) code than what the question currently has).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.