Can I pass a variable in a template binding?

前端 未结 4 567
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-15 10:45

I know this isn\'t a good method to use long term, but for troubleshooting, is there any way I can pass a simple string while binding a template and then access it as a variable

相关标签:
4条回答
  • 2021-02-15 10:54

    For people reading on later versions of knockout, this would appear to be a good usecase for components vs templates.

    0 讨论(0)
  • 2021-02-15 10:58

    You can pass arbitrary data to a template, while maintaining the currently applied viemodel, by supplying a composition to the data parameter of the binding.

    You could for example wrap the template content in a with binding, bound to the composed $data property, creating a new binding context. This way, the currently applied bindings don't need to be updated.

    ko.applyBindings({
      fruits: ['banana', 'orange']
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    
    <div data-bind="template: { name: 'tmplOne', data: { myModelData: $data, myVar: 'apple' } }"></div>
    
    <script type="text/html" id="tmplOne">
      <!-- ko with: myModelData -->
        <span>My model</span>
        <ul data-bind="foreach: fruits">
          <li data-bind="text: $data"></li>
        </ul>
        <div>
          <span>My custom data:</span>
          <span data-bind="text: $parent.myVar"></span>
        </div>
      <!-- /ko -->
    </script>

    0 讨论(0)
  • 2021-02-15 11:01

    Use

    <!-- ko template: { name: tmplOne, templateOptions: {myvar: 'apple'} } -->
    

    More here: http://www.knockmeout.net/2011/03/quick-tip-reusing-template-by-passing.html

    0 讨论(0)
  • 2021-02-15 11:18

    You can supply a data parameter to the template binding and define an object literal if you want just like you are doing:

    <!-- ko template: { name: tmplOne }, myvar: 'apple' -->
    

    instead do this:

    <!-- ko template: { name: tmplOne, data: { myvar: 'apple' } } -->
    

    http://knockoutjs.com/documentation/template-binding.html

    0 讨论(0)
提交回复
热议问题