Foreach loop for binding key/value ObservableArray

2019-08-10 20:25发布

I'm trying to create a menu based on an observablearray filled with menu items. I also have div's which should get visible when the menu item is clicked, the problem is that these div's had visible bindings based on the array position of their specified menu item. This worked till i tried to remove/add some menu item to the array and i realised it is a horrible way of binding the menu items to the divs.

As a solution I decided to use a key/value observablearray so it wouldn't matter if a menu item was added or removed. I got this to work for single menu items with bindings but I can't get it to work with a foreach loop (to show a set of menu items).

Here is the Fiddle: http://jsfiddle.net/Dennis50/uu2u90my/

For example I would get this to work:

<h2 data-bind="text: $root.parentArray()[0].project.childObservableArray()[0].klimaat.destUrl()"></h2>

But when I try to get it to work for multiple menu items I can't get this to work:

<div data-bind="foreach: $root.parentArray()[0].project.childObservableArray()[0]">
   <h2 data-bind="text: destUrl()"></h2>    
</div>

So how do I bind these menuitems using the foreach loop and is it even the best solution to this problem?

标签: knockout.js
1条回答
Juvenile、少年°
2楼-- · 2019-08-10 21:26

You can follow this simple and nice solution

View

<ul data-bind='foreach:Menu'>
    <li data-bind="text:Description,click:Action"></li>
</ul>   

<div data-bind="visible:FirstDiv">
    Hi !i am first div
</div>

<div data-bind="visible:SecondDiv">
    And i am the second one
</div> 

Viewmodel

function Menu(obj){
    var self = this
    self.Description = ko.observable(obj.Description)
    self.Action = obj.Action
}
var vm = function(){
    var self = this
    self.Menu = ko.observableArray([])
    self.FirstDiv = ko.observable(true)
    self.SecondDiv = ko.observable(false)

    self.LoadData = function(){
        self.Menu.push(new Menu({ Description: 'Home', Action : self.EnableFirstDiv }))
        self.Menu.push(new Menu({ Description: 'About', Action : self.EnableSecondDiv }))
    }

    self.EnableFirstDiv = function (data) {
        self.SecondDiv(false)
        self.FirstDiv(true)
    }

    self.EnableSecondDiv = function (data) {
        self.FirstDiv(false)
        self.SecondDiv(true)
    }        

    self.LoadData();
}    
$('document').ready(function () {
    ko.applyBindings(new vm())
})

Fiddle Demo

查看更多
登录 后发表回答