Suresh Kamrushi
Suresh Kamrushi

Reputation: 16076

knockout nested foreach binding is not working

I have html as: JSfiddle

<ul data-bind="foreach: Items">
    <li data-bind="click: setTextColor, text: 'Color: ' + color"></li>
     <ul data-bind="foreach:add">
         <li data-bind="text:test"></li>
    </ul>
</ul>

and JS as below:

var Item = function(color) {
    var self = this;
    self.color = String(color);
    self.setTextColor = function(item, event) {
        console.log(item.color);
        $(event.target).css('color', color);
    };
},
     add = function (test){
        
        this.test = String (test);
};
ko.applyBindings(new function() {
    this.Items = ko.observableArray([
        {new Item('red'),ko.observableArray(new add('colore'),new add('is'),new add('red'))},
        {new Item('blue'),ko.observableArray(new add('colore'),new add('is'),new add('blue'))},
        {new Item('green'), ko.observableArray(new add('colore'),new add('is'),new add('green'))}
    ]);
}());

But it is not populating the data. Can any one tell me what is the problem!!!

Upvotes: 0

Views: 1074

Answers (2)

samjudson
samjudson

Reputation: 56853

I'd do it something like this:

var Item = function(color, a) {
    var self = this;
    self.color = String(color);
    self.setTextColor = function(item, event) {
        console.log(item.color);
        $(event.target).css('color', color);
    };
    self.add = ko.observableArray(ko.utils.arrayMap(a, function(item) { return new add(item); }));
},
add = function (test){
    this.test = String (test);
};
ko.applyBindings(new function() {
    this.Items = ko.observableArray([
        new Item('red',['colore','is','red']),
        new Item('blue',['colore','is','blue']),
        new Item('green', ['colore','is','green'])
    ]);
}());

JSFiddle: http://jsfiddle.net/ENQzc/

Upvotes: 1

Anders
Anders

Reputation: 17554

Firebug or Chrome console maybe?

SyntaxError: missing : after property id
[Stanna vid fel]  

{new Item('red'),ko.observableArray(new add('colore'),new add('is

/Wnzrr/1/show/ (line 49, col 14)

Your array definition at bottom is really strange, what are you trying todo?

Upvotes: 0

Related Questions