如何绑定仅可用键的挖空视图模型

How to bind Knockout viewModel for only available keys?

本文关键字:模型 视图 何绑定 绑定      更新时间:2023-09-26

我正在使用MVC中的.cshtml动态创建淘汰data-bind属性。我只想绑定那些在viewModel中可用的属性,我再次从休息的WCF的结果动态创建这些属性。

因此,视图中可能存在也可能没有可用的键模型例如:创建<span data-bind="text: cli"></span>

但是当我绑定视图模型时,我收到一个错误,如"在视图模型中找不到'cli'属性"。但是,我想仅当该键首先存在于 viewModel 中时才绑定该属性。

 $(document).ready(function () {
            debugger;
            $.ajax({
                cache: false,
                type: "GET",
                async: false,
                dataType: "json",
                url: requestURL,
                success: function (data) {
                    debugger;
                    if (data.GetCircuitCheckStatusResponse.Status.HasErrors == false) {
                        networkData = data.GetCircuitCheckStatusResponse.Response.RunningStatus.networkData;
                        diagnosticData = data.GetCircuitCheckStatusResponse.Response.RunningStatus.diagnosticData;
                        diagnosticsInfo = {};
                        //To Create boxPanel Datas
                        for (var i = 0; i < networkData.length; i++) {
                            diagnosticsInfo[networkData[i].ItemTitle] = networkData[i].itemValue;
                        }
                        //To Bind the data using Knockout 
                    }
                },
                error: function (xhr) {
                    debugger;
                    alert(xhr.responseText);
                }
            });
            debugger;
            var viewModel = ko.mapping.fromJS(diagnosticsInfo);
            ko.applyBindings(viewModel);
            // Every time data is received from the server:
            //ko.mapping.fromJS(data, viewModel);
        });
@foreach (var nameValue in childContainer.NameValueImageItemsList)
                                {
                                    var cssClass = "nameValueItem floatLeft" + " " + nameValue.DataBindName;
                                    <div class="@cssClass" style="">@nameValue.DisplayName</div>
                                    <div class="@cssClass" style="width: 200px; margin-right: 10px;" ><span data-bind="text: CLI"></span></div>
                                    <div class="@cssClass" style="width: 200px; margin-right: 10px;">
                                        <a>
                                            @if (nameValue.IconImageURL != null && nameValue.IconImageURL != "")
                                            {
                                                <img src="@nameValue.IconImageURL" alt="i"/>   
                                            }
                                        </a>
                                    </div>
                                    <div class="clearBOTH"></div>
                                }

这是一个非常简单的方法:

ko.applyBindings({
  description: 'some description'
  // ,title: 'my title'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Description: <span data-bind="text: description"></span><br />
Title: <span data-bind="text: !!title ? title : ''"></span>

一个相关的选项可能是在视图模型上创建safeTitle计算属性:

var Vm = function() {
  var self = this;
  self.description = 'my description';
  //self.title = 'my title';
  self.safeTitle = ko.computed(function() {
    return !!self.title ? self.title : '';
  });
};
ko.applyBindings(new Vm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Description: <span data-bind="text: description"></span><br />
Title: <span data-bind="text: safeTitle"></span>

此外,您还可以使用函数来执行此操作,因此您不必为每个属性创建可观察量:

var Vm = function() {
  var self = this;
  self.description = 'my description';
  //self.title = 'my title';
  self.safeGet = function(prop) {
    return !!self[prop] ? self[prop] : '';
  };
};
ko.applyBindings(new Vm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Description: <span data-bind="text: description"></span><br />
Title: <span data-bind="text: safeGet('title')"></span>

请注意,如果

这些属性是可观察的,则此代码将略有不同,如果可以是其中之一,则甚至会有所不同(且复杂)。

另一种选择可能是查看这篇博文的第 3 点,关于包装现有绑定:您可以创建另一个"文本"绑定来防止这种情况。

附言。我会仔细重新考虑你的设计。属性是"可选"的事实很可能与某些域概念有关。

.PPS。您也可以考虑使用 Null 对象模式服务器端,这个问题完全消失了。

购买力平价。这是规避该问题的最后一种方法,(合乎逻辑,但)令我惊讶:

ko.applyBindings({
  desc: 'some description'
  // ,title: 'my title'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Description: <span data-bind="text: $data.desc"></span><br />
Title: <span data-bind="text: $data.title"></span>

这就是它对我的工作方式:

 <span data-bind="text: $data['@nameValue.DataBindName'] "></span>