我有Customer
这样的模型(简化):
public int CustomerAcc { get; set; }
public string Name { get; set; }
public int Blocked { get; set; }
Blocked
有3个可能的值:0,1,2。0表示没问题,1表示客户已被警告,2表示客户被阻止。
然后我有一个淘汰视图模型,如此:
function SearchCustomerViewModel() {
var self = this;
self.custTerm = ko.observable('');
self.customers = ko.observableArray([]);
self.excludeClosedAccs = ko.observable(true);
self.search = function () {
$.ajax({
url: "/api/SearchCustomers",
data: { id: self.custTerm },
type: "GET",
success: function (data) {
self.customers(data);
}
});
}
}
$(document).ready(function () {
var viewModel = new SearchCustomerViewModel();
ko.applyBindings(viewModel);
$("#btnSearch").click({ handler: viewModel.search });
});
这提供了一个简单的搜索API来搜索我的客户存储库。我有一个名为excludeClosedAccs
的属性,我默认设置为true,我想在我的视图中排除任何Blocked
等于2的帐户。这是我视图中的复选框,当未被攻击时,将其包括在我的结果中。这是我的观点:
<div id="body">
<h1>Customer Search</h1>
<div>
Search:<input type="text" data-bind="value: custTerm" />
<input type="button" id='btnSearch' title="Search" value="Search" />
</div>
<div data-bind="visible: customers().length > 0">
<span data-bind="text: customers().length"></span>
customers found.
<label>Exclude Closed Accounts: <input data-bind="checked: excludeClosedAccs" type="checkbox"/></label>
</div>
<div id="results-container" data-bind="template: { name: 'customer-results', foreach: customers }"></div>
</div>
<script type="text/html" id="customer-results">
<div>
<h6 data-bind="text: CustomerAcc"></h6>
<p>Company Name: <span data-bind="text: Name"></span></p>
<!-- ko if: Blocked > 0 -->
<p>Blocked: <span data-bind="text: Blocked"></span></p>
<!-- /ko -->
</div>
</script>
是否可以在我的self.customers
数组上应用过滤器来执行我希望或我必须单独发出的请求,一个用于排除被阻止的帐户以及一个包含它们的帐户?
答案 0 :(得分:2)
您希望在视图模型中使用计算方法,如果excludeClosedAccs为false,则返回完整集合,或者根据您建议的条件过滤数组:
function SearchCustomerViewModel() {
// properties
var self = this;
self.custTerm = ko.observable('');
self.customers = ko.observableArray([]);
self.excludeClosedAccs = ko.observable(true);
self.customersToShow = ko.computed(function () {
if (!self.excludeClosedAccs()) {
return self.customers();
}
return ko.utils.arrayFilter(self.customers(), function (customer) {
return customer.Blocked == 0 || customer.Blocked == 1;
});
});
// methods
self.search = function () {
$.ajax({
url: "/api/SearchCustomers",
data: { id: self.custTerm },
type: "GET",
success: function (data) {
self.customers(data);
}
});
}
}
$(document).ready(function () {
var viewModel = new SearchCustomerViewModel();
ko.applyBindings(viewModel);
$("#btnSearch").click({ handler: viewModel.search });
});