属性改变的可见性没有更新
本文关键字:更新 可见性 改变 属性 | 更新日期: 2023-09-27 17:50:38
我在过去的3个小时里搜索了互联网,寻找解决方案,但一无所获。我发现最接近我正在寻找的是在这里:是否有可能对布尔ViewModel属性的否定("!")可见数据绑定?。我还没能让这个解决方案起作用。
我试图隐藏一个dom元素基于一个属性的子列表的视图模型。
function ViewModel() {
var self = this;
this.addSocialMediaLink = function () {
self.EditProjectSocialMediaViewModels.push({ ProjectId: 0, ProjectSocialMediaId: 0, SocialMediaType: '', Url: '', Deleted: false });
}.bind(this);
self.removeSocialMediaLink = function (socialLink) {
socialLink.Deleted = true;
}
}
$(function () {
ko.bindingHandlers.hidden = {
update: function (element, valueAccessor) {
ko.bindingHandlers.visible.update(element, function () {
return !ko.utils.unwrapObservable(valueAccessor());
});
}
};
var myViewModel = new ViewModel();
$.getJSON('@Url.Action("GetProject")' + '/ProjectId', null, function (data) {
ko.mapping.fromJS(data, {}, myViewModel);
ko.applyBindings(myViewModel);
});
});
Server Side VM
public class EditProjectSocialMediaViewModel
{
public int ProjectId { get; set; }
public int ProjectSocialMediaId { get; set; }
[Required]
[Url]
[StringLength(100, ErrorMessage = "The {0} must be no longer than 100 characters.")]
public string Url { get; set; }
public bool Deleted { get; set; }
}
Dom: <div data-bind='foreach: EditProjectSocialMediaViewModels'>
<input type="text" class='required form-control' data-bind='value: Url, hidden: Deleted, attr: { name: "EditProjectSocialMediaViewModels["+$index()+"].Url" }' />
<a href="#" data-bind="click: $root.removeSocialMediaLink">Delete</a>
<br />
</div>
<button data-bind='click: addSocialMediaLink'>Add Social Media Link</button>
当单击链接时,值会改变并正确存储。
可视性不会改变,因为被删除的属性是不可观察的,所以将其设置为可观察的。
function ViewModel() {
var self = this;
self.EditProjectSocialMediaViewModels = ko.observableArray([]);
this.addSocialMediaLink = function () {
self.EditProjectSocialMediaViewModels.push({
ProjectId: 0,
ProjectSocialMediaId: 0,
SocialMediaType: '',
Url: '',
Deleted: ko.observable(false)
});
}.bind(this);
self.removeSocialMediaLink = function (socialLink) {
socialLink.Deleted(true);
}
}
http://jsfiddle.net/U8j5G/