0

Trying to include an add button within my knockout template as shown below although I get the following error. If I move the button outside the template and below the form it works strangely.. Any ideas why this is happening? Thanks,

Template

<script type="text/html" id="mytemplate">   

<table data-bind="foreach: Keywords">
<tr>
  <td data-bind="text: $data"></td>
  <td>
      <a href="#" data-bind="click: $root.delete">Delete</a>
  </td>
</tr>
</table>

<input data-bind="value: toAdd" > <button data-bind="click: add">Add</button>   

</script>

Mark up

@using (Html.BeginForm...)      
{
  <div data-bind="template: { name: 'mytemplate', data: mydata}"></div>
}

Error

Error: Error: Unable to parse bindings.
Message: ReferenceError: toAdd is not defined;
Bindings value: value: toAdd

Javascript (onload)

window.Helper = {
    Start: function (tag) {
        var viewModel = viewModel(tag);
        window.helper.ViewModel = viewModel; 
        viewModel.toAdd = ko.observable();
        viewModel.add = function () {  
            ...
        };
    ko.applyBindings(viewModel);
James Radford
  • 1,815
  • 4
  • 25
  • 40
  • In your error you have `toAdd`. Where do you have this property in your ViewModel? – nemesv Jan 03 '14 at 13:44
  • You probably already know this, but that code is going to look for a `toAdd` property on the current binding object (same object that has the `keywords` property). Can you post more of your view model code? – Joseph Gabriel Jan 03 '14 at 13:44
  • i've added where the apply binding is used. – James Radford Jan 03 '14 at 13:53
  • try `$root.toAdd` and that should work if my assumptions are correct – Armand Jan 03 '14 at 13:56
  • 1
    Where do you call `ko.applyBindings` is irrelevant in this case... what we need to know how exactly your viewmodel looks like with all the properties what you have in your `mytemplate`. Because you have binding context problems so you probably need to write `` or `` (the same is true for the `data-bind="click: add"`) but without seeing your viewmodel it is hard to tell... – nemesv Jan 03 '14 at 13:56
  • newesv: I think this is it.. Just checking it out now.. – James Radford Jan 03 '14 at 14:06

1 Answers1

1

In your template binding you are inside of the context of the mydata property.

However your toAdd and add are defined on the root level so you need to use $root (or $parent depending of the nesting level) in your bindings to access them:

<input data-bind="value: $root.toAdd" /> 
<button data-bind="click: $root.add">Add</button>

You can read more the binding contexts in the documentation.

nemesv
  • 138,284
  • 16
  • 416
  • 359