在我看来:
<!-- 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>
我的viewModel:
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。它只应在我点击“保存”时执行,因此点击:绑定。这是怎么回事?
答案 0 :(得分:2)
当您打开并关闭括号“saveAboutMe(userId)”时,您正在执行该功能,您只需在点击装订上设置“saveAboutMe”功能的名称。
如果您希望将全局变量传递给“保存”功能,可以采取哪些措施使其更加清洁。
userId = @Html.Raw(Json.Encode(User.Identity.Name));
在点击装订中:
<a data-bind="click: function(){saveAboutMe(userId);}">save</a>
您在这里所做的是定义一个匿名函数,当用户单击“save”锚点时,该函数将调用“saveAboutMe”。你和你正在做的事情之间的区别在于,匿名函数只是定义,而不是执行。
另一个更干净的事情是将userId添加到你的ko ViewModel中,并在函数中引用它:
self.saveAboutMe = function (username) {
console.log(self.userId); // this should work if you add your userId to your view model.
dataservice().updateAboutMe(username, self.aboutMe());
self.isEditingAboutMe(false);
};