Knockout.js-在asp.net mvc3部分视图上多次绑定viewModel的基础知识

Knockout.js-在asp.net mvc3部分视图上多次绑定viewModel的基础知识,knockout.js,knockout-2.0,Knockout.js,Knockout 2.0,我在项目中使用knockout.js将模型绑定到视图。基本上,在document.ready函数中,我使用以下代码: var viewModel = { firstName: ko.observable("John") listofChildren=ko.observablearray() }; ko.applyBindings(viewModel); dataService.getChildren(viewModel); // This

我在项目中使用knockout.js将模型绑定到视图。基本上,在document.ready函数中,我使用以下代码:

 var viewModel = {
        firstName: ko.observable("John")
        listofChildren=ko.observablearray()
    };
    ko.applyBindings(viewModel);
    dataService.getChildren(viewModel); // This is no good need to move to partial view
我可以在大多数页面上使用上述viewModel。然而,我有一个要求,对于一个局部视图,我们通过Jquery调用第三方web服务,并填充上面的listOfChildren属性

问题是,此时对web服务的调用发生在document.ready上,这意味着每次页面刷新都会调用web服务。我只想在用户加载部分视图时进行调用

我试图在部分视图页面上移动对第三方webservice的调用,但它显示viewModel为null

dataService.getChildren(viewModel); //where dataService is a function which uses ajax call to webservice and populates the listofChildren array.

有人能帮助我如何最好地实现上述功能吗?

将调用移动到部分视图后,将调用移动到
getChildren
无法找到
viewModel
,原因有两个:

  • viewModel
    的作用域是
    document.ready
    函数,在该函数之外不可见
  • getChildren
    的调用发生在创建
    viewModel
    之前
  • 以下是我的建议:将
    getChildren
    调用留在
    document.ready
    中,但仅当部分视图存在时才执行它,方法是搜索仅存在于部分视图中的内容。如果你找到了,就把孩子们装进去

    if ($('#SomethingInPartialView').length) {
        dataService.getChildren(viewModel);
    }