Foreach loop for binding key/value ObservableArray

三世轮回 提交于 2019-12-13 18:36:27

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/25607057/foreach-loop-for-binding-key-value-observablearray

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!