在淘汰映射中加载数据之前阻止html加载

时间:2017-12-24 14:59:44

标签: javascript jquery knockout.js

HTML:

BOOST_ROOT

JavaScript的:

<div id="knockoutBinding">
    <div class="toolbar" data-bind="template: 'user-portfolio-entry' "></div>
</div>

<script id="user-portfolio-entry" type="text/html">
<!-- ko if: vm.currentPortfolioEntry().hasOwnProperty('Step') -->
//other stuff
<!-- /ko -->
</script>

我收到错误:

  

未捕获的TypeError:无法处理绑定&#34; template:function   (){return&#39; user-portfolio-entry&#39; }&#34;消息:无法处理绑定   &#34; if:function(){return   vm.currentPortfolioEntry()。hasOwnProperty(&#39; Step&#39;)}&#34;消息:不能   读取属性“hasOwnProperty&#39;为null

当执行ajax成功的行var UserPortfolioViewModel = function () { var self = this; self.currentPortfolioEntry = ko.observable(null); $.ajax({ type: "POST", url: getPortfolioEntryUrl, data: JSON.stringify(data1), dataType: "json", contentType: "application/json", success: function (response) { self.currentPortfolioEntry(ko.mapping.fromJS(response)); }, error: function (data) { alert("fail"); } }); } var vm; $(function () { vm = new UserPortfolioViewModel(); ko.applyBindings(vm, $("#knockoutBinding")[0]); }); 时,我可以在控制台中看到self.currentPortfolioEntry(ko.mapping.fromJS(response));的值,但那时html已经完成加载,我无法在html中获取数据。

如何在ajax成功后加载html,以便可以映射属性。或者以其他方式解决此错误?

1 个答案:

答案 0 :(得分:2)

您可以重构if以测试变量是否退出如下:

<!-- ko if:  vm.currentPortfolioEntry() && vm.currentPortfolioEntry().hasOwnProperty('Step') -->