我正在使用Knockout这样的选择:
<hr class="light" />
在HTML部分中是:
function journal(data) {
this.id = ko.observable(data.ID);
this.name = ko.observable(data.Name);
}
var self = this;
self.journals = ko.observableArray([]);
$.getJSON("/JournalEntries/GetJournalsList", function (data) {
var mappedJournals = $.map(data, function (item) { return new journal(item) });
self.journals(mappedJournals);
});
self.getData = function(journalid) {
alert(journalid);
};
它不带有ID,只是'[Object object]'
我做错了什么?
答案 0 :(得分:2)
你通常不想在淘汰赛中以这种方式对事件作出反应。
如果您想对<select>
中所选值的更改作出反应,请将所选值保存到observable(通过value
绑定)并订阅该observable(或基本计算值)在那个可观察的)。
function Journal(data) {
this.id = ko.observable(data.ID);
this.name = ko.observable(data.Name);
}
function ViewModel() {
var self = this;
// data
self.journals = ko.observableArray();
self.selectedJournal = ko.observable();
// subscriptions
self.selectedJournal.subscribe(function (journal) {
if (journal) alert( journal.id() );
});
// init
var newJournals = ko.utils.arrayMap([
{ID: 1, Name: "Item 1"},
{ID: 2, Name: "Item 2"},
{ID: 3, Name: "Item 3"},
{ID: 4, Name: "Item 4"},
], function(item) { return new Journal(item); });
self.journals(newJournals);
}
ko.applyBindings(new ViewModel());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="
options: journals,
optionsCaption: 'Choose...',
optionsText: 'name',
value: selectedJournal
"></select>
<hr>
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
&#13;
答案 1 :(得分:1)
self.journals是一个Observable数组,就像你需要推送的javascript中的普通数组一样,项目进入数组
self.journals.push(mappedJournals);