jquery eventbinding in collapsible menu while using knockout template

不打扰是莪最后的温柔 提交于 2019-12-13 05:06:21

问题


I have the following view in MVC , where I am trying to render a collapsible menu.

@{
    ViewBag.Title = "Details";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


@section Scripts {
  @Scripts.Render("~/bundles/jqueryval")
  <script type="text/javascript" src="@Url.Content("~/Scripts/knockout-2.2.0.js")"></script> 
  <script type="text/javascript" src="@Url.Content("~/Scripts/moment.js")"></script> 

 <script type="text/html" id="problemTemplate">
    <li>ID# <span data-bind="text: ProblemID"/>
    <ul data-bind="template: { name: 'visitTemplate', foreach: VisitList, as: 'visit' }"></ul>
    </li>
</script>

<script type="text/html" id="visitTemplate">
    <li> Visit <span data-bind="text: VisitID"></span> 
    </li>
</script>


  <script type="text/javascript">

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

      })


  </script>
}

<div class="content">
    <div id="title">
        <h1>Details </h1>
    </div>
    <div>
        <ul id="usernav" data-bind="template: { name: 'problemTemplate', foreach: problems, as: 'problem' }"></ul>

    </div>
    <div class="demo-section">
    </div>


</div>

I get a regular list with all nodes showing. It appears that the $('#usernav').find('ul').hide(); event is never fired after the knockout template is rendered. How do I fix this?


回答1:


This happens because the problems observableArray is not populated at the moment of applyBindings. You need to hide it when the json response comes back from the server. The easiest way to do this would be with a customBinding. Fiddle: http://jsfiddle.net/hv9Dx/4/

html:

<script type="text/html" id="problemTemplate">
    <li>ID# <span data-bind="text: ProblemID"/>
    <ul data-bind="template: { name: 'visitTemplate', foreach: VisitList, as: 'visit' }, hideInitial:{}"></ul>
    </li>
</script>

Notice the hideInitial:{} customBindinng.

And do this before applyBindings:

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

Also, you no longer need the $('#usernav').find('ul').hide(); call.




回答2:


Or you can change

self.problems= ko.observableArray();

TO:

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


来源:https://stackoverflow.com/questions/19730723/jquery-eventbinding-in-collapsible-menu-while-using-knockout-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!