使用ko.PureComputed列表作为Kendo ComboBox的数据源

问题描述 投票:0回答:1

我正在尝试获取下面的selectedJobs列表,作为下面的kendoComboBox的数据源。但是,列表的值未加载,并且没有出现错误,因此我不确定出什么问题。我正在尝试的可能吗?我可以不使用ko.pureComputed()返回的列表作为数据源吗?另外,即使selectedJobs具有此字段,也不会将Jobid识别为dataValueField的字段。谢谢!

pageModel.newServiceModel.selectedJobs = ko.pureComputed(function () {
    return pageModel.newServiceModel.selectedAccount() ? pageModel.newServiceModel.selectedAccount().jobs : null;
});

var source = new kendo.data.DataSource(pageModel.newServiceModel.selectedJobs);

$("#newServiceJobs").kendoComboBox({
    placeholder: "Select One",
    filter: "contains",
    suggest: true,
    change: pageModel.newServiceModel.JobSelectionChange,
    dataSource: source,
    //dataValueField: jobid,
    dataTextField: name
});
knockout.js kendo-datasource kendo-combobox
1个回答
0
投票

以下是修正现有代码的两种方法:

  • 要访问pureComputed,您需要像pageModel.newServiceModel.selectedJobs()这样的函数来调用它。您可以将其直接传递为dataSource属性。
  • [dataValueFielddataTextField选项需要字符串(例如“ jobid”和“ name”)
  • 如果您希望控件对您的selectedJobs计算的更改做出反应,那么您将需要订阅更改并更新控件,例如:
pageModel.newServiceModel.selectedJobs.subscribe( function(newData) {
     $("#newServiceJobs").data( "kendoComboBox" ).dataSource.data( newData );
});

以下是显示您的情况的摘要。单击“填写所选帐户”按钮以填充selectedAccount观察栏。

const viewModel = {
	selectedAccount: ko.observable(),
  clearSelectedAccount() {
  	viewModel.selectedAccount( null );
  },
  fillSelectedAccount() {
      viewModel.selectedAccount({
      	jobs: [
        	{ jobid: "1", name: "one" },
        	{ jobid: "2", name: "two" }
      	]
    	});
  }
};

viewModel.selectedJobs = ko.pureComputed(function () {
    const account = viewModel.selectedAccount();
    return account ? account.jobs : [];
});

ko.applyBindings( viewModel );

$("#newServiceJobs").kendoComboBox({
    placeholder: "Select One",
    filter: "contains",
    suggest: true,
    change: null,
    dataSource: viewModel.selectedJobs(),
    dataValueField: "jobid",
    dataTextField: "name"
});

viewModel.selectedJobs.subscribe( newData => {
	$("#newServiceJobs").data( "kendoComboBox" ).dataSource.data( newData );
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://kendo-labs.github.io/knockout-kendo/css/kendo.default.min.css" rel="stylesheet"/>
<link href="https://kendo-labs.github.io/knockout-kendo/css/kendo.common.min.css" rel="stylesheet"/>
<script src="https://kendo-labs.github.io/knockout-kendo/js/kendo.all.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<button data-bind="click: fillSelectedAccount">Fill Selected Account</button>
<button data-bind="click: clearSelectedAccount">Clear Selected Account</button>

<hr/>

<input id="newServiceJobs" />

[另一个可能的选择是查看knockout-kendo,它将为您提供一些从Knockout到Kendo UI的基本绑定,例如:http://kendo-labs.github.io/knockout-kendo/web/ComboBox.html。该库负责使控件和视图模型保持同步,并避免您需要通过jQuery手动管理kendo控件。

© www.soinside.com 2019 - 2024. All rights reserved.