Reputation: 1820
I'm using Knockout with a select like so:
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);
};
And in HTML part is:
<select data-bind="options: $root.journals, optionsCaption: 'Choose...', value: 'id', optionsText: 'name', event:{ change: $root.getData }"></select>
And it doesn't come back with an ID, just '[Object object]'
What am I doing wrong?
Upvotes: 0
Views: 2051
Reputation: 338128
You generally don't want to react to events this way in knockout.
If you want to react to a change in the selected value in a <select>
, save the selected value to an observable (via the value
binding) and subscribe to that observable (or base computed values on that 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());
<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>
Upvotes: 2
Reputation: 2405
self.journals is an Observable array, just like a normal array in javascript you need to push, the item into the array
self.journals.push(mappedJournals);
Upvotes: 1