Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout foreach with alternating classes

Tags:

knockout.js

Could someone more knowledgeable in knockout tell me if I'm doing this the correct way?

I am trying to add float left and float right class alternately in a foreach directive - here is my binding. Am I way off mark? Is there a better approach?

<a data-bind="css:{'pull-left':$index()%2 == 0,'pull-right':$index()%2 == 1}, attr:{href:$data.url}">

Loving knockout - btw

Any help much appreciated.

like image 972
Chin Avatar asked May 28 '26 01:05

Chin


1 Answers

The way that you are doing it will work. If you want a cleaner way to do it, then you could either create a computed observable on your view model that returns the right values or even better a custom binding that handles this logic for you.

A sample of a custom binding where you can pass what you want to use as the index might look like:

ko.bindingHandlers.float = {
    init: function(element, valueAccessor, allBindings, data, context) {
        var index, floatValue;

        index = valueAccessor();

        floatValue = ko.computed(function() {
           var left = ko.utils.unwrapObservable(index) % 2 === 0; 
           return left ? "left" : "right";
        });

        ko.applyBindingsToNode(element, { 
            style: {
                cssFloat: floatValue
            }                
        });
    }        
};

Here is a sample: http://jsfiddle.net/rniemeyer/B8YHc/

If you want to use bootstrap's classes, then you could do it like: http://jsfiddle.net/rniemeyer/VdLNQ/. They just do float left/right, so either way should be fine.

like image 52
RP Niemeyer Avatar answered May 31 '26 12:05

RP Niemeyer