在Jquery模板中找不到knockout.js和属性

时间:2011-08-10 16:20:56

标签: jquery knockout.js jquery-templates

我正在使用以下代码获取“caseStudy未定义”。我必须添加完整前缀app.viewModel.caseStudy.showFlawDetails以免错误。

 app.viewModel.caseStudy = {};
        app.viewModel.caseStudy.cases = ko.observableArray();
        app.viewModel.caseStudy.selectedCaseId = ko.observable(0);
        app.viewModel.caseStudy.selectedCase = ko.mapping.fromJS(caseModel);
app.viewModel.caseStudy.showFlawDetails = function (index) {
        console.log(index);
    };
ko.applyBindings(app.viewModel);

<div class="Flaws" data-bind='template: { name: "flawTemplate", data: caseStudy.selectedCase.Flaws }'>
    </div>
    <script id="flawTemplate" type="text/html">
        {{each(index, value) $data}}
        <div class="flaw">
        <div class="Title" data-bind="click: caseStudy.showFlawDetails(index)"> ${value.Title} </div>
        <div class="Items">
            <div>Title: <input type="text" data-bind="value: value.Title" /></div>
            <div>Check: <input type="text" data-bind="value: value.Check" /></div>
            <div>Instructor: <input type="text" data-bind="value: value.Instructor" /></div>
            <div>Keys: <input type="text" data-bind="value: value.Keys" /></div>
            <div>Opponent Init: <input type="text" data-bind="value: value.OpponentInit" /></div>
            <div>Opponent Justification: <input type="text" data-bind="value: value.OpponentJustif" /></div>
            <div>Opponent Communication: <input type="text" data-bind="value: value.OpponentComm"/></div>
            <div>Hint: <input type="text" data-bind="value: Hint"/></div>
            <div>Opponent Incorrect Hint: <input type="text" data-bind="value: value.OpponentIncorrectHint"/></div>
            <div>Prompt: <input type="text" data-bind="value: Prompt" /></div>
            <div>PromptCompletion: <input type="text" data-bind="value: value.PromptCompletion"/></div>
            <div>Opponent Incorrect Prompt: <input type="text" data-bind="value: value.OpponentIncorrectPrompt"/></div>
        </div>
        </div>
        {{/each}}
    </script>

1 个答案:

答案 0 :(得分:1)

flawTemplate范围内caseStudy.selectedCase.Flaws,因此当您放置caseStudy.showFlawDetails时,不会将其视为Flaws的属性或全局属性。

因此,如果app.viewModel.caseStudy.showFlawDetails具有全局范围(由于它适用于您),您可以使用app引用它。

否则,一个好的选择是通过templateOptions传递函数。所以,你会这样做:

data-bind='template: { name: "flawTemplate", data: caseStudy.selectedCase.Flaws, templateOptions: showFlawDetails: caseStudy.showFlawDetails } }'>

然后,您可以使用$item.showFlawDetails

访问它

单击(和事件)绑定也期望您将其传递给函数。在您的情况下,您正在传递执行该函数的结果。在这里进一步回答:knockout.js calling click even when jquery template is rendered