Я пытаюсь использовать knockoutjs 1.2.l и со следующим кодом
$(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>
Выдает исключение.
Невозможно проанализировать атрибут привязки. Сообщение: TypeError: selectedCategory () не определено;
Значение атрибута: text: selectedCategory (). 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.