我正在构建一个 Web 应用程序,并希望将 UI 转换为使用 Knockout JS。我是淘汰赛的菜鸟,所以请善待!
通常我会加载一个员工列表(使用 PHP),然后如果选择了一个员工,我会使用 JQuery 找到该员工的 ID,然后对我的后端进行 AJAX 调用,填写结果框并将其向下滑动。
有没有办法在 Knockout 中复制这种行为?
我正在构建一个 Web 应用程序,并希望将 UI 转换为使用 Knockout JS。我是淘汰赛的菜鸟,所以请善待!
通常我会加载一个员工列表(使用 PHP),然后如果选择了一个员工,我会使用 JQuery 找到该员工的 ID,然后对我的后端进行 AJAX 调用,填写结果框并将其向下滑动。
有没有办法在 Knockout 中复制这种行为?
一个样板供您开始,使用 jQuery 和 Knockout。
HTML
<ul data-bind="foreach: employees">
<li data-bind="css: {current: $data == $root.selected()}, click: $root.selected">
#<span data-bind="text: id"></span> - <span data-bind="text: name"></span>
</li>
</ul>
<div data-bind="slideVisible: ! loading(), html: employee_detail"></div>
CSS
.current {
background: blue;
color: white;
}
ul>li {
list-style: none;
}
JS
$(function() {
// for your requirment on sliding animation, this slideVisible is copied from http://knockoutjs.com/documentation/custom-bindings.html
ko.bindingHandlers.slideVisible = {
update: function(element, valueAccessor, allBindings) {
var value = valueAccessor();
var valueUnwrapped = ko.unwrap(value);
var duration = allBindings.get('slideDuration') || 400;
if (valueUnwrapped == true)
$(element).slideDown(duration); // Make the element visible
else
$(element).slideUp(duration); // Make the element invisible
}
};
var vm = {
employees: ko.observableArray([
// build your initial data in php
{id: 1, name: 'John'},
{id: 2, name: 'Tom'},
{id: 3, name: 'Lily'},
{id: 4, name: 'Bob'}
]),
selected: ko.observable(), // a placeholder for current selected
loading: ko.observable(false), // an indicator for ajax in progress
employee_detail: ko.observable() // holder for content from ajax return
};
// when user selects an employee, fire ajax
vm.selected.subscribe(function(emp) {
var emp_id = emp.id;
// ajax starts
vm.loading(true);
$.ajax('/echo/html/?emp_id='+emp_id, {
// just a simulated return from jsfiddle
type: 'POST',
data: {
html: "<b>Employee #" + emp_id + "</b><p>Details, bla bla...</p>",
delay: 0.2
},
success: function (content) {
// update employee_detail
vm.employee_detail(content);
},
complete: function() {
// ajax finished
vm.loading(false);
}
});
});
ko.applyBindings(vm);
});
这听起来类似于本淘汰教程中的文件夹和电子邮件的向下钻取。