这是我的自定义绑定:
ko.bindingHandlers.alert = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {
$(element).attr({ style: "display:none" });
ko.applyBindingsToNode(element, { with: valueAccessor() }, context);
return { controlsDescendantBindings: true };
},
update: function (element, valueAccessor) {
var data = ko.unwrap(valueAccessor());
if (data) {
$(element).attr({ "class": "alert " + ko.unwrap(data.success) });
$(element).show();
}
else
$(element).hide();
}
};
这是我传递给绑定的警报obj:
var alertObj = {
success: "",
image: "",
message: ""
};
var initialDataObj = {
success: "alert-success",
fail: "alert-danger"
};
var Alert = function (initialData) {
var self = this;
self.success = initialData.success;
self.successImage = initialData.successImage;
self.fail = initialData.fail;
self.failImage = initialData.failImage;
self.setAlert = function (success, message) {
var alert = {};
$.extend(alert, alertObj);
alert.success = success ? self.success : self.fail;
alert.image = success ? self.successImage : self.failImage;
alert.message = message;
return alert;
};
}
这是我设置警报的方式:
self.alert(alert.setAlert(true, "Role removed"));
这是我的HTML:
<div class="alert alert-success" data-bind="alert: $root.alert">
<img data-bind="attr: { src: $root.image }" alt="" width="16" style="float: left;">
<p style="float: left; margin-left: 10px;" data-bind="text: $root.message"></p>
<div style="clear: both;">
</div>
</div>
它当前为警报选择了正确的类,但它没有显示图片或文本,某些地方的绑定会丢失。
答案 0 :(得分:2)
通过简单的逻辑,当您访问image
和message
时,不需要$ root,因为警报块内的绑定上下文是alert
返回的.setAlert
对象
<div class="alert alert-success" data-bind="alert: $root.alert">
<img data-bind="attr: { src: image }" alt="" width="16" style="float: left;">
<p style="float: left; margin-left: 10px;" data-bind="text: message"></p>
<div style="clear: both;"></div>
</div>
很确定它会有所帮助。