【发布时间】:2015-08-18 15:51:38
【问题描述】:
在这里提琴:http://jsfiddle.net/0gmbbv5w/
我有一个从数据库中提取并绑定到 <select> 的对象
var NoticeType = function (noticeType) {
this.NoticeTypeId = ko.observable(noticeType.NoticeTypeId);
this.NoticeLevel = ko.observable(noticeType.NoticeLevel);
this.FriendlyName = noticeType.FriendlyNoticeLevel;
}
这些将像这样填充在我的视图模型中
NoticeType: new NoticeType({
NoticeTypeId: 2,
NoticeLevel: 'info',
FriendlyNoticeLevel: 'Informational'
})
NoticeTypeId 存储在数据库中,NoticeLevel 是绑定到元素的 CSS 类。 'FriendlyName` 是显示为选项文本的内容。
添加新通知时,选择类型时,NoticeLevel 应该随着下拉列表的变化而改变 CSS 类。
<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>
在选择 CSS 类时,我能找出绑定它的唯一方法是删除 optionsValue 绑定。我的问题来自选择要编辑的项目时,绑定无法正常工作,因此编辑时的NoticeType始终显示为“基本”通知类型,因为它无法映射数据返回。
有什么方法可以做到这一点吗?还是我在这里遗漏了一些明显的东西?当添加一个新的,或者选择一个进行编辑和更改选择值时,它将正确更新 CSS 类。最初选择一个进行编辑时,它没有正确绑定 CSS 类。
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()) != "";
});
}
【问题讨论】:
-
你能做个小提琴吗?
-
添加在最顶部。
标签: javascript css knockout.js