如何获取嵌套视图模型的实例 - 淘汰赛

时间:2013-06-10 10:45:55

标签: javascript knockout.js

视图的标题后跟带子菜单的部分。 viewmodels的设计如下:

SettingsViewModel = function (pName) {
    var self = this;
    self.productName = ko.observable(pName), //heading
    self.sections = ko.observableArray([
            { checkboxID: ko.observable(), checkboxIDState: ko.observable(), sectionname: ko.observable(), sectionState: ko.observable() } 
        ]),  //submenus

    self.Addsections = function (checkboxid, sIdState, sName, sState) {
        this.sections.push({ checkboxID: checkboxid, checkboxIDState: sIdState, sectionname: sName, sectionState: sState });
    }
};


function MainViewModel() {
    var self = this;
    self.products = ko.observableArray([]);
    self.AddProducts= function (pname) {
        self.products.push(new SettingsViewModel(pname));
    }
};


$(document).ready(function () {
        VM = new MainViewModel();
        ko.applyBindings(VM, document.getElementById("divd"));
    data= []; //some dummy data
    CallMEnus(data);

 });

 function CallMEnus(data) {
        var str = "";

        $(data).each(function (index, products) {
            VM.AddProducts(products.name);

                        $(products.section).each(function (index, section) {

                            var ChkboxId = "data";  
                            var chkboxIdState = 'datt';
                            var chkboxIdState += " checked";
                        }
            //how to call the products add section method?
                            VM.products()[index].Addsections(ChkboxId, chkboxIdState, section.name, section.state);  

                        });

        });

我需要从MainViewModel实例调用嵌套的SettingsViewModel的AddSections方法。怎么做到这一点?

提前致谢。

2 个答案:

答案 0 :(得分:1)

您的问题是来自各个部分循环的参数index会隐藏index来自产品循环。只需使用其他参数名称:

function CallMEnus(data) {
    var str = "";

    $(data).each(function (index, products) {
        VM.AddProducts(products.name);

        $(products.section).each(function(i, section) { // here
            var id = "data";
            var state = "checked";
            VM.products()[index].Addsections(id, state, section.name, section.state);
        });
    });
};

Fiddle

答案 1 :(得分:-1)

我会使用EventAggregator来解耦视图模型,我已经编写了这个轻量级的EventAggregator

http://jsfiddle.net/wJtun/4/

订阅:

MyApp.eventAggregator.subscribe(MyApp.DeleteCustomerMessage, this.customerDeleted, this);

发布:

MyApp.eventAggregator.publish(new MyApp.DeleteCustomerMessage(this));