2
我想使用knockoutjs 1.2.l與下面的代碼knockoutjs拋出無法解析綁定屬性
$(function() {
var viewModel = {
categories: ko.observableArray([
{"Selected": false, "Text": "Rooms", "Value": "1"},
{"Selected": false, "Text": "Automobile", "Value": "2"},
{"Selected": false, "Text": "Buy & Sell", "Value": "3"},
{"Selected": false, "Text": "Tutions", "Value": "4"},
{"Selected": false, "Text": "Immigration", "Value": "5"}
]),
initialData: {
"Description": null,
"SubCategoryId": 0,
"Title": null,
"UserId": 0,
"AdTypeId": 0,
"AddressId": null,
"SubCategory": null,
"User": null,
"AdType": null,
"Address": null,
"Id": 0,
"CreatedOn": "\/Date(1307627158991)\/",
"CreatedBy": 0,
"LastUpdatedOn": "\/Date(1307627158991)\/",
"LastUpdatedBy": 0
},
chosenCategory: ko.observable()
};
ko.applyBindings(viewModel); // Makes Knockout get to work
});
Follwing是HTML
<div id="createAdDiv">
<form action="/Ads/Create" method="post"> <p>
You've chosen: <b data-bind="text: chosenCategory().Text"></b>(Value: <span data-bind='text: chosenCategory().Value'></span>)
</p>
<div data-bind="visible: chosenCategory"> <!-- Appears when you select something -->
You have chosen a country with population
<span data-bind="text: chosenCategory() ? chosenCategory().Text : 'unknown'"></span>.
</div>
<fieldset>
<div class="editor-label">
<label for="SubCategoryId">Choose a Sub Category</label>
</div>
<div class="editor-field">
<select data-bind="options: categories,optionsCaption:'Choose...',optionsText: 'Text',value:chosenCategory" data-val="true" data-val-number="The field Choose a Sub Category must be a number." data-val-required="The Choose a Sub Category field is required." id="SubCategoryId" name="SubCategoryId"></select>
<span class="field-validation-valid" data-valmsg-for="SubCategoryId" data-valmsg-replace="true"></span>
</div>
</fieldset>
</form></div>
拋出異常。
Unable to parse binding attribute. Message: TypeError: chosenCategory() is undefined; Attribute value: text: chosenCategory().Text
但是,如果我更改JavaScript來下面它的工作原理
$(function() { var viewModel = { categories: ko.observableArray([{"Selected":false,"Text":"Rooms","Value":"1"},{"Selected":false,"Text":"Automobile","Value":"2"},{"Selected":false,"Text":"Buy & Sell","Value":"3"},{"Selected":false,"Text":"Tutions","Value":"4"},{"Selected":false,"Text":"Immigration","Value":"5"}]) ,initialData: {"Description":null,"SubCategoryId":0,"Title":null,"UserId":0,"AdTypeId":0,"AddressId":null,"SubCategory":null,"User":null,"AdType":null,"Address":null,"Id":0,"CreatedOn":"\/Date(1307628565958)\/","CreatedBy":0,"LastUpdatedOn":"\/Date(1307628565958)\/","LastUpdatedBy":0} }; viewModel.chosenCategory = ko.observable(viewModel.categories); ko.applyBindings(viewModel); // Makes Knockout get to work });
我下面僅knockout.js網站的例子。