使用挖空模板时,在可折叠菜单中使用jquery eventbinding

我在MVC中有以下视图,我正在尝试渲染可折叠菜单。

@{ ViewBag.Title = "Details"; Layout = "~/Views/Shared/_Layout.cshtml"; } @section Scripts { @Scripts.Render("~/bundles/jqueryval")    
  • ID#
    • Visit
    • function MyViewModel() { var self = this; self.problems= ko.observableArray(); $.getJSON("/api/clients/1/history", self.problems); } $(document).ready(function () { ko.applyBindings(new MyViewModel()); $('#usernav').find('ul').hide(); $('li').live("click", function (e) { $(this).children('ul').toggle(); e.stopPropagation(); }); }) }

      Details

        我得到一个显示所有节点的常规列表。 它似乎是$('#usernav').find('ul').hide(); 渲染挖空模板后永远不会触发事件。 我该如何解决?

        发生这种情况是因为在applyBindings时没有填充problems observableArray。 当json响应从服务器返回时,您需要隐藏它。 最简单的方法是使用customBinding。 小提琴: http : //jsfiddle.net/hv9Dx/4/

        HTML:

          

        注意hideInitial:{}

        并在applyBindings之前执行此操作:

          ko.bindingHandlers.hideInitial = { init:function(element){ console.log(element); $(element).hide(); } } 

        此外,您不再需要$('#usernav').find('ul').hide(); 呼叫。

        或者你可以改变

         self.problems= ko.observableArray(); 

        至:

         self.problems= ko.observableArray([]);