2011-08-10 64 views
0

我得到「caseStudy未定義」與下面的代碼。我必須添加完整的前綴app.viewModel.caseStudy.showFlawDetails以避免錯誤。knockout.js和財產沒有被發現在jquery模板

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

裏面你flawTemplate範圍是caseStudy.selectedCase.Flaws,所以當你把caseStudy.showFlawDetails,它沒有發現作爲Flaws或全局屬性。

因此,如果app具有全局作用域(它似乎適用於您),那麼您可以使用app.viewModel.caseStudy.showFlawDetails來引用它。

否則,一個好的選擇是通過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