【发布时间】:2015-01-30 03:41:04
【问题描述】:
我制作了一个名为statusAlert 的“简单”警报小部件,用于在数据未能按预期到达时显示消息。到目前为止,我无法将数据输入其中。我认为我可以将一个可观察对象注入到小部件中,并在可观察对象设置为对象时显示和填充小部件。但我还没有弄清楚如何让这个概念发挥作用。
statusAlert/view.html
<div class="alert alert-danger" role="alert" data-bind="visible: content">
<button type="button" class="close" aria-label="Close" data-bind="click: hide"><span aria-hidden="true"><i class="fa fa-times"></i></span></button>
<button type="button" class="close" aria-label="Show Details" data-bind="click: showDetails"><span aria-hidden="true"><i class="fa fa-info-circle"></i></span></button>
<p class="lead" data-bind="text: header"></p>
<p data-bind="text: message"></p>
<p data-bind="visible: detailsIsVisible"><pre data-bind="text: details"></pre></p>
</div>
statusAlert/viewmodel.js
define(['knockout'], function (ko) {
var ctor = function () {
this.content = ko.observable();
this.detailsIsVisible = ko.observable(false);
};
// Methods.
// Activate event handler.
ctor.prototype.activate = function () {
//TODO What goes here?
};
// Destroying the content will result in the alert becoming invisible.
ctor.prototype.hide = function () {
this.content(null);
};
ctor.prototype.showDetails = function () {
this.detailsIsVisible(true);
};
// Data fields: Computed observables that extract data from 'content.'
ctor.prototype.header = ko.computed(function () {
if (this.content) {
return this.content() ? this.content().header : null;
}
return null;
}, this);
ctor.prototype.message = ko.computed(function () {
if (this.content) {
return this.content() ? this.content().message : null;
}
return null;
}, this);
ctor.prototype.details = ko.computed(function () {
if (this.content) {
return this.content() ? this.content().details : null;
}
return null;
}, this);
return ctor;
});
父视图模型的相关代码
var statusAlertObservable = ko.observable();
$.ajax({
success: function (data, status, request) {
if (data.ResponseStatus.ErrorCode) {
statusAlertObservable({
header: "Service reports error.",
message: data.ResponseStatus.Message,
details: data.ResponseStatus
});
} else {
// (do something with data)
}
},
error: function (data, status, error) {
statusAlertObservable({
header: "Error getting application data.",
message: error,
details: data
});
}
});
return {
statusAlertObservable: statusAlertObservable,
//...
}
父视图的相关代码
<div data-bind="statusAlert: 0"></div>
【问题讨论】: