0

I have a case here

http://jsfiddle.net/jX6m2/6/

I have an observable array, and i have a single component, which is to vouch for the presence of a value in the given observable array and change the css if it exists so.

for ex in this script i am to check, if the word "hello" exists in the array and if it does than change the css to blue

SCRIPT

function VM() {
    var arrInterests = 'hello,world'.split(',');    
    this.interests = ko.observableArray(arrInterests);
};

ko.applyBindings((new VM()));

HTML

<p class="green" data-bind="css: { 'blue': interests() === 'hello'}">Hello exists:
</p>

CSS

.green {
    background-color: green;
    border:2px solid red;
}

.blue {
    background-color: blue;
    border:2px solid red;
}

1 Answer 1

1

You should use Array.indexOf to search for a value within arrays:

interests().indexOf('hello') >= 0

Of course, you should put this code in a computed property inside of the viewmodel:

function VM() {
    var arrInterests = 'hello,world'.split(',');    
    this.interests = ko.observableArray(arrInterests);
    this.contains = function(value) {
        return ko.computed(function() {
            return this.interests().indexOf(value) >= 0;
        });
    };
};

// usage

<p class="green" data-bind="css: { 'blue': contains('hello') }">Hello exists:</p>
<p class="green" data-bind="css: { 'red': contains('world') }">world exists:</p>
....
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.