javascript - 带模型的 knockout 计算列

标签 javascript c# knockout.js knockout-mvc

我的 MVC C# 解决方案中有一个具有以下属性的模型

public class RegistrationRequirementModel
{
    public string LoadIntent { get; set; }
    public string Francophone { get; set; }
    public string Gender { get; set; }

    public RegistrationRequirementModel(L09RegistrationRequirement requirement)
    {
        LoadIntent = requirement.LoadIntent;
        Francophone = requirement.Francophone;
        Gender = requirement.Gender;
    }
}

在我的 javascript 中,我可以调用模型并显示数据,但是当涉及到使用某些计算函数时,它就会失败。

Javascript

    var registrationRequirementModel = {
        frenchData:  ko.observable(""),
        genderData:  ko.observable(""),
        loadIntentData:  ko.observable(""),

        isMissingData: ko.computed(function () {
            if (this.frenchData() == "") { return true };
            if (this.genderData() == "") { return true };
            if (this.loadIntentData() == "") { return true };
            return false;
        },this),

    }

   $(document).ready(function () {

        ko.applyBindings(registrationRequirementModel, document.getElementById("RegistrationSurveyContent"));

        $.ajax({
            url: getStudentRegRequirementsUrl,
            type: "GET",
            contentType: jsonContentType,
            dataType: "json",
            success: function (data) {
                if (!account.handleInvalidSessionResponse(data)) {
                    registrationRequirementModel.frenchData(data.Francophone);
                    registrationRequirementModel.genderData(data.Gender);
                    registrationRequirementModel.loadIntentData(data.LoadIntent);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                if (jqXHR.status != 0)
                    $('#notificationHost').notificationCenter('addNotification', { message: "Unable to retrieve registration requirement.", type: "error" });
            }
        });
    });

HTML

<table style="width:100%">
    <tbody>
        <tr>
            <td data-bind="text: loadIntentData"></td>
            <td data-bind="text: frenchData"></td>
            <td data-bind="text: genderData"></td>
        </tr>
    </tbody>
</table>

目的是在缺少数据时显示 html。然而,当我激活此代码时,计算列一直说 frenchData 不是函数。我的观点可以在我的 html data-bind="visible: isMissingData" 中使用。但不幸的是。我可以从我的数据中读取事件。

这是我对 api 的调用

 public async Task<JsonResult> GetRegistrationRequirementAsync()
 {
     string StudentID = CurrentUser.PersonId;
     try
     {
         var requirement = await ServiceClient.L09GetRegistrationRequirementAsync(StudentID);
         RegistrationRequirementModel registrationRequirementModel = new RegistrationRequirementModel(requirement);
         return Json(registrationRequirementModel, JsonRequestBehavior.AllowGet);
      }
      catch (Exception e)
      {}
}

最佳答案

frenchData is not a function 控制台错误源于 KnockoutJS ViewModel 的设置方式。本质上,普通可观察量下方的计算函数 isMissingData 有一个新的 this 内部作用域上下文,它不反射(reflect) registrationRequirementModel 的相同外部作用域> 对象。

enter image description here

要解决此问题,您应该从使用对象文字切换到构造函数,以便可以将this ViewModel范围分配给一个 self/that 变量可以缓解范围问题。然后通过 KO Apply Bindings 实例化新存储的 ViewModel,您现在可以在 AJAX 成功后访问该 ViewModel:

function registrationRequirementModel() {
  var self = this;
  self.frenchData = ko.observable("");
  self.genderData = ko.observable("");
  self.loadIntentData = ko.observable("");

  self.isMissingData = ko.computed(function() {
    if (self.frenchData() == "") {
      return true
    };
    if (self.genderData() == "") {
      return true
    };
    if (self.loadIntentData() == "") {
      return true
    };
    return false;
  }, this);
}

$(document).ready(function() {
  var vm = new registrationRequirementModel();
  ko.applyBindings(vm, document.getElementById("RegistrationSurveyContent"));

  // replace with endpoint
  var jsonData = {
    Francophone: "Francophone",
    Gender: "Male",
    LoadIntent: "LoadIntent"
  };

  if (handleInvalidSessionResponse(jsonData)) {
    vm.frenchData(jsonData.Francophone);
    vm.genderData(jsonData.Gender);
    vm.loadIntentData(jsonData.LoadIntent);
  }
});

function handleInvalidSessionResponse(data) {
  if (typeof data !== "undefined") return true;
  return false;
}

下面是场景的模拟 JSFiddle http://jsfiddle.net/ajxrw39m/3/

关于javascript - 带模型的 knockout 计算列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54350217/

相关文章:

javascript - 将对象从 Html 传递到指令

C# 将 DataGridView 保存到文本文件

c# - 找不到对 System.Runtime.Serialization.Formatters.Binary 的引用

knockout.js - Knockoutjs中的observable数组和映射插件有什么用

javascript - XMLHttpRequest Post 上 send() 数据参数的最大长度

javascript - Angular ng-repeat 基于另一个 ng-repeat

javascript - 克隆范围不起作用

c# - 加密 JWT 安全 token 支持的算法

knockout.js - 具有 "as"别名的 Foreach 绑定(bind)在 IE9 中无法正常工作

javascript - Knockout.js 双向绑定(bind) : Number Formatted as String