即使在呈现jquery模板时,knockout.js也会调用click [英] knockout.js calling click even when jquery template is rendered

查看:98
本文介绍了即使在呈现jquery模板时,knockout.js也会调用click的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在模板渲染时甚至会为showFlawDetails触发点击?

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>

推荐答案

单击(和事件)绑定希望您将其传递给函数引用,而不是对该函数的实际求值.

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

因此,在您的情况下,它试图将click事件设置为等于app.viewModel.caseStudy.ShowFlawDetails(index)结果.

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); }"

或者,如果您不喜欢匿名函数,那么您将需要找到一种将函数移至caseStudy对象并将索引放在caseStudy对象上的方法,以便您可以直接访问它.如果有帮助,请参见

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.

此外,这是通过订阅对其父对象observableArray的更改来维护对象上的index属性的示例: http://jsfiddle.net/rniemeyer/CXBFN/

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/

这篇关于即使在呈现jquery模板时,knockout.js也会调用click的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆