敲除+ MVC-您不能多次将绑定应用于同一元素 [英] Knockout + MVC - You cannot apply bindings multiple times to the same element

查看:62
本文介绍了敲除+ MVC-您不能多次将绑定应用于同一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MVC视图:

@model MG.ViewModels.Profile.ProfileDetailsViewModel
<div>
<h4>About Me</h4>
<!-- ko if: !isEditingAboutMe() -->
<p data-bind="text: aboutMe()">@Model.AboutMe</p>
@if (Model.CurrentUserCanEdit)
{
    <a data-bind="click: editAboutMe">edit</a>
}
<!-- /ko -->
<!-- ko if: isEditingAboutMe() -->
@Html.TextBoxFor(model => model.AboutMe, new { data_bind = "value: aboutMe" })
<a data-bind="click: saveAboutMe">save</a>
<a data-bind="click: cancelAboutMe">cancel</a>
<!-- /ko -->
</div>

<script type="text/javascript">ko.applyBindings(@Html.Raw(Json.Encode(Model)));</script>

我的ProfileVm Javascript:

My ProfileVm Javascript:

function ProfileVm() {
var self = this;

self.saveAboutMe = function() {
    self.isEditingAboutMe(false);
};

self.cancelAboutMe = function() {
    self.isEditingAboutMe(false);
};

self.isEditingAboutMe = ko.observable(false);
self.editAboutMe = function() {
    self.isEditingAboutMe(true);
};

}

$(document).ready(function () {
    ko.applyBindings(new ProfileVm());
})

我正在通过捆绑包在Layout.cshtml中加载ProfileVm:

I'm loading ProfileVm in Layout.cshtml via a bundle:

    @Scripts.Render("~/bundles/viewmodels")

我两次调用ko.applyBindings()-一次在我看来直接将MVC模型绑定到可剔除的可观察对象,另一次绑定ProfileVm的属性.

I'm calling ko.applyBindings() twice - once directly in my view to bind the MVC Model to knockout observables, and the other to bind the properties of the ProfileVm.

我在做什么错了?

推荐答案

@RPNiemeyer对问题进行了很好的解释.但是我认为,与其尝试应用两个视图模型,不如将一个视图模型组合为一个简单的解决方案.像这样:

@RPNiemeyer has provided an excellent explanation of the problem. But I think that instead of trying to apply two view models, the simpler solution is to combine your view models into one. Something like this:

function ProfileVm(model) {
    var self = this;
    self.aboutMe = ko.observable(model.AboutMe);

    self.saveAboutMe = function() {
        self.isEditingAboutMe(false);
    };

    self.cancelAboutMe = function() {
        self.isEditingAboutMe(false);
    };

    self.isEditingAboutMe = ko.observable(false);
    self.editAboutMe = function() {
        self.isEditingAboutMe(true);
    };

}

$(document).ready(function () {
    ko.applyBindings(new ProfileVm(@Html.Raw(Json.Encode(Model))));
})

这篇关于敲除+ MVC-您不能多次将绑定应用于同一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆