0

I'm new to knockout template engine and I've run into an issue.

I have a container that contains text input with clickable hints. My aim is to change input text with link caption after it is clicked by user.

html code snippet:

<script type="text/html" id="query-input-template">
  <input data-bind="value: query" type="search" placeholder="query"></input>
  <span>
    Example: <span data-bind="template: { name: 'hint-template', data: { hint: hints[0] }}"></span> 
          or <span data-bind="template: { name: 'hint-template', data: { hint: hints[1] }}"></span>
  </span>
</script>

<script type="text/html" id="hint-template">
  <a href="#" data-bind="text: hint, click: vm.query.bind($data, hint)"></a>
</script>

<div id="search-container" data-bind="template: { name: 'query-input-template' }"></div>

js code snippet:

viewModel = function() {
  var self = this;

  self.hints = [ "Test query 1", "Test query 2" ];

  self.query = ko.observable();
}

var vm = new viewModel();

ko.applyBindings(vm, document.getElementById('search-container'));

codepen version: https://codepen.io/YungJ/pen/VjpEaq?editors=1010

This code works properly and I'm quite satisfied with the result. But I'm sure that it can be rewritten appropriately. The thing I'm not satisfied with the second template's "vm.query" binding. I want to pass view model from upper template to get rid of this and recieve more clean query.bind($data, hint) binding

Yung J
  • 13
  • 4
  • What is your question exactly? Are you looking for a code review? – Jeroen Jun 29 '16 at 08:04
  • On a side note, I recommend against using `vm` like that in your view, because in essence you're referencing a global variable. Instead try to encapsulate your js code snippet in an iife, and use `$root` instead of `vm` (or if possible leave off the scope). – Jeroen Jun 29 '16 at 08:05
  • "$root" is exactly that I'm looking for. Thanks for such quick response. – Yung J Jun 29 '16 at 08:15

0 Answers0