0

在 ko.mapping.fromJS 行之后找出为什么会导致未定义的 viewModel 的最佳方法是什么?

rawJSON 在 chrome js 对象资源管理器中看起来不错

    var viewModel = ko.mapping.fromJS(rawJSON);
        viewModel = decorateViewModel(viewModel);
        ko.applyBindings(viewModel);

在铬中查看:

rawJSON: Object
   Companies: Array[1]
   CompaniesFollowing: Array[0]
   DisplayName: null
   DateCreated: "2013-03-11T21:50:21.9"
   __proto__: Object
viewModel: undefined



  function decorateViewModel(viewModel){
            viewModel.CompaniesFollowing().forEach(function(self) {
                self.isFollowing = ko.observable(true);
                self.toggleIsFollowing = function () {
                    if(self.isFollowing()){
                        unFollowCompany()}
                    else{
                        followCompany();
                    }
                    self.isFollowing(!self.isFollowing());//reverse it so the user can see the button text change
                };
                self.followButtonText = ko.computed(function () {
                    return self.isFollowing() ? "Unfollow" : "Follow";
                });
                self.styleClass = ko.computed(function () {
                    return self.isFollowing() ? "radius button" : "radius secondary button";
                });
            });

原始JSON:

  var rawJSON = { "Companies" : [ { "DateCreated" : "2013-03-11T21:53:31.123",
     "Description" : "eee",
     "EquityOffered" : 3.0,
     "FollowingUsers" : null,
     "Id" : 1,
     "InvestmentFound" : 0.0,
     "InvestmentSought" : 3333.0,
     "LogoFileName" : "4ED564E6-CDBB-4045-8E55-9581B7FA13E0.jpg",
     "Name" : "Model Adapt",
     "SocialDetails" : null
   } ],
  "CompaniesFollowing" : [  ],
  "DateCreated" : "2013-03-11T21:50:21.9",
  "DateUpdated" : "2013-03-11T21:50:21.9",
  "DisplayName" : null,
  "FullName" : null,
  "HomeAddress" : null,
  "Id" : 1,
  "Investor" : { "AvailableFunds" : 0.0,
      "DateCreated" : "2013-03-11T22:30:07.273",
      "DateUpdated" : "2013-03-11T22:30:07.273",
      "Description" : "kbibkb",
      "FollowingUsers" : [  ],
      "Id" : 1,
      "Interests" : "bukb",
      "LogoFileName" : null,
      "Name" : "giu",
      "Skills" : "kbku",
      "SocialDetails" : null
    },
  "InvestorsFollowing" : [ { "AvailableFunds" : 0.0,
        "DateCreated" : "2013-03-11T22:30:07.273",
        "DateUpdated" : "2013-03-11T22:30:07.273",
        "Description" : "kbibkb",
        "FollowingUsers" : [  ],
        "Id" : 1,
        "Interests" : "bukb",
        "LogoFileName" : null,
        "Name" : "giu",
        "Skills" : "kbku",
        "SocialDetails" : null
      } ],
  "LogoFileName" : null,
  "MiniAbout" : null,
  "UserName" : "Master_"
}
4

1 回答 1

1

是否肯定var viewModel = ko.mapping.fromJS(rawJSON);会导致 viewmodel 为空,或者是viewModel = decorateViewModel(viewModel);因为我会出现您的 decorateViewModel 方法没有返回视图模型,这将导致它在该行被处理后为空。

于 2013-03-12T20:18:31.357 回答