knockout.js calling click even when jquery template is rendered

好久不见. 提交于 2019-12-23 17:33:56

问题


Why would the click even get fired for showFlawDetails when the template renders?

app.viewModel.caseStudy.showFlawDetails = function (index) {
        console.log(index);
        app.viewModel.caseStudy.selectedFlaw(index);
    };

<script id="flawTemplate" type="text/html">
    {{each(index, value) $data}}
    <div class="flaw">
    <div class="Title" data-bind="click: app.viewModel.caseStudy.showFlawDetails(index)"> Flaw: ${value.Title} </div>
    <div class="Items" data-bind="visible: app.viewModel.caseStudy.selectedFlaw() == index">
     <div>Title: <input type="text" data-bind="value: value.Title" /></div>
     <div>Check: <input type="text" data-bind="value: value.Check" /></div>
    {{each(index1, value1) value.Details}}
         <div>${value1.Key}: <input type="text" data-bind="value: value1.Value" /></div>
    {{/each}}
    </div>
    </div>
    {{/each}}
</script>

回答1:


The click (and event) bindings expect that you pass it a reference to a function and not the actual evaluation of it.

So, in your case it is trying to set the click event equal to the result of app.viewModel.caseStudy.ShowFlawDetails(index).

To make this work you would either need to wrap it in an anonymous function like:

click: "function() { app.viewModel.caseStudy.showFlawDetails(index); }"

or if you don't like the anonymous function, then you would need to find a way to move the function to the caseStudy object and put an index on your caseStudy object, so you can access it directly. If it helps look at the Avoiding anonymous functions in event bindings in this post of mine.

Also, here is a sample of maintaining an index property on an object by subscribing to changes to its parent observableArray: http://jsfiddle.net/rniemeyer/CXBFN/



来源:https://stackoverflow.com/questions/7016678/knockout-js-calling-click-even-when-jquery-template-is-rendered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!