【发布时间】:2014-10-18 05:10:47
【问题描述】:
在这里淘汰新手。我有一个显示客户信息的页面。
1st div should be displayed when customer info is present.
2nd div should be displayed when no customers are displayed
//1st Div
<div id="custInfoList" data-role="content"
data-bind="foreach: customers, visible : customers().length > 0">
<p data-bind="text: $data.info"></p>
</div>
//2nd Div
<div id="empty" data-role="content"
data-bind="visible: customers().length === 0 ">
<p>No Customer Information</p>
</div>
我的模型是这样的:
var myModel = {
customers : ko.observableArray();
}
..在页面加载时我添加了这个逻辑:
//On Page Load, call AJAX to populate the customers
//customers = {jsonData}
我的页面正在使用 jQuery Mobile。我唯一的问题是第一次显示页面时,显示第二个 div。当 Ajax json 数据返回时,它就被隐藏了。
是否可以在 ajax 仍在加载且数据尚未返回时隐藏第二个 div?
更新 2
在相关的说明中,我尝试了我刚刚从网上阅读的 KO HTML 模板
<!-- ko if: customers().length -->
<div id="custInfoList" data-role="content"
data-bind="foreach: customers, visible : customers().length > 0">
<p data-bind="text: $data.info"></p>
</div>
<!-- /ko -->
<div id="empty" data-role="content"
data-bind="if: customers().length === 0">
<p>No Customer Information</p>
</div>
但还是失败了。有什么想法缺少什么吗?
更新 3 我尝试更新@shriek 在他的小提琴http://jsfiddle.net/t0wgLt79/17/ 中展示的内容@
<!-- ko if: customers() -->
<div id="custInfoList" data-role="content" data-bind="foreach: customers">
<p data-bind="text: $data"></p>
</div>
<!-- /ko -->
<div id="empty" data-role="content" data-bind="if: customers().length === 0" style="display: none;">
<p>No Customer Information</p>
</div>
<button data-bind="click:popCustomers">Populate</button>
我的 JS:
$.support.cors = true;
var test = {
customers: ko.observableArray(),
popCustomers: function () {
for (var i = 0; i < 3; i++) {
this.customers.push(i);
}
},
popByAjax: function () {
console.log("Calling JSON...");
$.getJSON("http://api.openweathermap.org/data/2.5/weather?id=2172797", function (data) {
console.log(data);
if (data.sys) {
this.customers.push(data.sys.country);
console.log("Loaded");
}
}.bind(this));
}
};
test.popByAjax();
ko.applyBindings(Object.create(test));
在初始加载时,会显示“AU”。现在将 weather?id=2172797 更改为 weather?id=21727971 使其无效。我注意到没有显示没有客户信息。
【问题讨论】:
-
将
style="display: none"添加到您的第二个 div。然后当 AJAX 调用返回时,$('#empty').show() -
嗨,James,谢谢,这就是我以前在 Jquery 中所做的。我在想 Knockout js 是否有某种方法可以解决这个问题,因为它们提供了“可见”绑定,然后不知何故我认为它正在被评估。否则,我可以删除“可见”并依赖 Jquery DOM 操作。
-
那么问题是在返回客户之前,长度为零,因此绑定显式显示了 div。我认为您正在尝试做的事情超出了 Knockout 的范围,所以我会使用 jQuery 来做。
-
是的,完全正确。这和我的想法是一样的。我只是问这个是否有办法。我尝试使用淘汰赛模板,但我似乎无法使其正常工作。
-
好的..我现在明白了。首先,如果您从
ko执行if,则不需要style:none,KO会自动为您执行此操作。您必须记住的另一件事是,如果您没有得到任何回复,您应该清空您的observableArray。请记住,您正在检查observableArary是否为空。这是一些修改的小提琴jsfiddle.net/4hmqdsup您可以继续询问您对代码的任何问题。