I have search the interwebs for the last 3 hours looking a solution and have found nothing. The closest I have found to what I am looking for is here: Is it possible to data-bind visible to the negation ("!") of a boolean ViewModel property? . And I haven't been able to get this solution to work.
I am trying to hide a dom element based on a property of a childlistitem of a viewmodel.
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>
The value changes and is stored correctly when clicking the link. But visibility does not change.