質問

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);
役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top