在房产更改KnockoutJs上没有更新可见性

时间:2014-03-18 02:57:45

标签: c# asp.net-mvc knockout.js

我已经搜索了最近3个小时的互联网寻找解决方案但没有找到任何结果。我找到的最接近我要找的是:Is it possible to data-bind visible to the negation ("!") of a boolean ViewModel property?。我还没有能够让这个解决方案起作用。

我试图根据viewmodel的childlistitem的属性隐藏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);
        });
    });

服务器端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>

单击链接时,值会更改并正确存储。但能见度不会改变。

1 个答案:

答案 0 :(得分:1)

可见性没有改变,因为删除的属性不可观察,使其可观察。

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/