在我看来:
<!-- 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(userId)">save</a>
<a data-bind="click: cancelAboutMe">cancel</a>
<!-- /ko -->
<script type="text/javascript">
$(document).ready(ko.applyBindings(new ProfileVm(@Html.Raw(Json.Encode(Model)))));
var userId = @Html.Raw(Json.Encode(User.Identity.Name));
</script>
我的视图模型:
function ProfileVm(model) {
var self = this;
self.aboutMe = ko.observable(model.AboutMe);
self.saveAboutMe = function (username) {
dataservice().updateAboutMe(username, self.aboutMe());
self.isEditingAboutMe(false);
};
self.cancelAboutMe = function() {
self.isEditingAboutMe(false);
};
self.isEditingAboutMe = ko.observable(false);
self.editAboutMe = function() {
self.isEditingAboutMe(true);
};
}
当我单击“编辑”时,DOM 会按预期更改,但会执行 saveAboutMe。只有当我点击“保存”时才应该执行它,因此点击:绑定。这是怎么回事?