2012-07-31 42 views
1

我正在构建一个web应用程序,并希望将UI转换为使用Knockout JS。我是淘汰赛中的一名总决赛,所以请客气一点!向下钻取Ajax风格的淘汰赛js

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

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

回答

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

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