在淘汰赛中深入了解Ajax风格

时间:2012-07-31 01:04:01

标签: javascript ajax

我正在构建一个Web应用程序,我希望将UI转换为使用Knockout JS。我是Knockout的总菜鸟,所以请善待!

通常我会加载一个员工列表(使用PHP),然后如果选择了一个员工,我会找到该员工的ID使用JQuery,然后make和AJAX调用我的后端,填写结果框并将其向下滑动

有没有办法在Knockout中复制这种行为?

2 个答案:

答案 0 :(得分:1)

启动的样板,使用jQuery和Knockout。

http://jsfiddle.net/5BHrc/6/

<强> 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);
});

答案 1 :(得分:0)

这听起来类似于this淘汰教程中文件夹和电子邮件发生的深入分析。