Check out the live example here: http://jsfiddle.net/0gmbbv5w/
In my application, I have an object retrieved from the database that I bind to a <select>
var NoticeType = function (noticeType) {
this.NoticeTypeId = ko.observable(noticeType.NoticeTypeId);
this.NoticeLevel = ko.observable(noticeType.NoticeLevel);
this.FriendlyName = noticeType.FriendlyNoticeLevel;
}
In the viewmodel, this object will be populated like this
NoticeType: new NoticeType({
NoticeTypeId: 2,
NoticeLevel: 'info',
FriendlyNoticeLevel: 'Informational'
})
The NoticeTypeId
is stored in the database, the NoticeLevel
is a CSS class bound to an element. 'FriendlyName' is displayed as the option text.
When adding a new notice, the NoticeLevel should change the CSS class as the dropdown selection changes.
<select data-bind="options: $parent.noticeTypes, optionsText: 'FriendlyName', value: noticeType"></select>
<div class="row-fluid">
<div class="span12">
<div class="alert" data-bind="css: alertLevel">
<h4>Just a reminder!</h4>
<span>This is a sample of what your notice will look like. The header is the Subject, and this text is the Message</span>
</div>
</div>
</div>
The issue I'm facing is with binding the CSS class when editing an existing notice. I have to remove the optionsValue
binding to make it work properly. When editing, the binding doesn't map back the data correctly, always showing the "basic" notice type.
Is there a way to resolve this issue? Am I overlooking something? Adding or editing a notice updates the CSS class correctly, but when initially editing a notice, the CSS class binding fails.
self.editNotice = function (item) {
self.noticeToAdd(new NoticeToAdd(ko.toJS(item)));
}
var NoticeToAdd = function (notice) {
var self = this;
if (!notice) {
notice = {};
}
this.noticeId = ko.observable(notice.NoticeId || notice.noticeId);
this.subject = ko.observable(notice.Subject || notice.subject);
this.body = ko.observable(notice.Body || notice.body);
this.publishDate = ko.observable(notice.PublishDate || notice.publishDate);
this.expireDate = ko.observable(notice.ExpireDate || notice.expireDate);
this.sticky = ko.observable(notice.Sticky || notice.sticky);
this.includeDismiss = ko.observable(notice.IncludeDismissAction || notice.includeDismiss || true);
this.noticeType = ko.observable(notice.NoticeType || notice.noticeType);
this.showDismissal = ko.observable(false);
//CSS binding
this.alertLevel = ko.pureComputed(function() {
return self.noticeType() ? 'alert-' + self.noticeType().NoticeLevel() : 'alert-basic';
});
this.ableToAddNotice = ko.pureComputed(function () {
return $.trim(self.body()) != "";
});
}