2

I have the following code in html:

<ul data-bind="template: {name:'location', foreach:locations}">
 </ul>

<script type="text/html" id="location">
      <li>
        <a href='#' id="search_results" data-bind='text: title' class='w3-bar-item'></a>
      </li>
</script>

and the following code in viewModel:

var locations = [ (location lists)
  ];

var viewModel = {
  title: ko.observable("Attractions in Seattle, Washington"),
  query: ko.observable(""),
};

viewModel.locations = ko.dependentObservable(function(){
    var search = this.query().toLowerCase();
          return ko.utils.arrayFilter(locations, function(location) {
            return location.title.toLowerCase().indexOf(search) >= 0;
          });
        }, viewModel);

    ko.applyBindings(viewModel);

as shown below:

demo

and there is the following code in one of my regular javascript functions

$("#search_results").on('click', function() {
      var context = ko.contextFor(this);
      for (var i = 0; i < placeMarkers.length; i++) {
        temp = placeMarkers[i].title + ", Seattle";
        if (temp == context.$data.title) {
          getPlacesDetails(placeMarkers[i], placeInfoWindow);
        }
      }
    });

I am trying to dynamically show the result based on what context the user clicks, but my function works only for the first item in the list (only Space Needle, in this case). How can I fix it? what would be knockout.js-ic way?

+

I wrote like this inside of viewModel:

show_infowindow: function() {
    var context = ko.contextFor(this);
    for (var i = 0; i < placeMarkers.length; i++) {
      temp = placeMarkers[i].title + ", Seattle";
      if (temp == context.$data.title) {
        getPlacesDetails(placeMarkers[i], placeInfoWindow);
      }
    }
  }

where

<a href='#' data-bind='text: title, click: show_infowindow' class='search_results w3-bar-item'></a>

and now nothing is working, how can I fix this?

Nicholas Huh
  • 85
  • 1
  • 2
  • 11
  • @IrkenInvader added some more explanations – Nicholas Huh Nov 09 '17 at 21:31
  • It looks like you'll have a lot of duplicate `id`s, try `class="search_results"` and adjusting your listener – IrkenInvader Nov 09 '17 at 21:45
  • could try `$('ul').on('click', '.search_results', function(){` so it'll work for dynamically created search results – IrkenInvader Nov 09 '17 at 21:47
  • @IrkenInvader it works great! thanks! Could you also explain what would be knockout.js-ic way to rewrite this jQuery, if possible? I am learning it and there's lots of confusion. – Nicholas Huh Nov 09 '17 at 21:53
  • 2
    Instead of using a jquery listener I would have the binding in your anchor tags read `data-bind='text: title, click: Clicked'` then create a function inside your localtion model called `Clicked` to handle it – IrkenInvader Nov 09 '17 at 21:58