jquery eventbinding in collapsible menu while usin

2019-09-04 10:24发布

问题:

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([]);