未捕获错误:您无法多次将绑定应用于同一元素

时间:2016-06-13 04:05:55

标签: javascript knockout.js

我怎样才能将我保留的两种模型结合起来用于两种不同的目的。一个用于文件上传,另一个用于来自不同对象的渲染数据.Below是我试过的各自的html和JS。

HTML部分

     <div class="well" data-bind="fileDrag: fileData">
        <div class="form-group row">
           <div class="col-md-6">
              <img style="height: 125px;" class="img-rounded  thumb" data-bind="attr: { src: fileData().dataURL }, visible: fileData().dataURL">
              <div data-bind="ifnot: fileData().dataURL">
                 <label class="drag-label">Drag file here</label>
              </div>
           </div>
           <div class="col-md-6">
              <input type="file" data-bind="fileInput: fileData, customFileInput: {
                 buttonClass: 'btn btn-success',
                 fileNameClass: 'disabled form-control',
                 onClear: onClear,
                 }" accept="application/pdf,image/*">
           </div>
        </div>
     </div>
     <button class="btn btn-default" data-bind="click: debug">Upload</button>
  </div>
  <div id="notification" style="display: none;">
     <span class="dismiss"><a title="dismiss this notification">X</a></span>
  </div>

     <!-- Collapsible Panels - START -->
     <div class="container">
        <div class="row">
           <div class="col-md-12">
              <div class="panel panel-primary">
                 <div class="panel-heading">
                    <h3 class="panel-title">Plan Details</h3>
                 </div>
                 <div class="panel-body">
                    <span class="glyphicon glyphicon-plus clickable" id="addPlanBtn"></span>
                    <span class="glyphicon glyphicon-remove clickable" id="removePlanBtn"></span>
                    <span class="glyphicon glyphicon-edit clickable" id="editPlanBtn"></span>
                    <table id="docsDataTable" class="table table-striped display" width="100%">
                       <thead>
                          <tr>
                              <th></th>
                              <th>Contract Document ID</th>
                              <th>Contract ID</th>
                              <th>Document Name</th>
                              <th>File Path</th>
                              <th>Comments</th>

                          </tr>
                       </thead>
                    </table>                        
                    <div class="modal fade" id="notificationDialog" role="dialog">
                       <div class="modal-dialog modal-sm">
                          <div class="modal-content">
                             <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" \>&times;</button>
                                <h4 class="modal-title">Notification</h4>
                             </div>
                             <div class="modal-body" id="notificationBody">


                             </div>
                             <div class = "modal-footer">
                                <button type = "button" class = "btn btn-primary" data-dismiss = "modal">
                                   Ok
                                </button>
                             </div>
                          </div>
                       </div>
                    </div>
                    <div class="modal fade" id="confirmBox" role="dialog">
                       <div class="modal-dialog modal-sm">
                          <div class="modal-content">
                             <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" \>&times;</button>
                                <h4 class="modal-title">Confirmation</h4>
                             </div>
                             <div class="modal-body" id="confirmBody">
                                   Selected rows will be made inactive.
                             </div>
                             <div class = "modal-footer">
                                <button type = "button" class = "btn btn-default" data-dismiss = "modal" id="confirmNoBtn">
                                   Cancel
                                </button>
                                <button type = "button" class = "btn btn-primary" data-dismiss = "modal" id="confirmYesBtn">
                                   Ok
                                </button>
                             </div>
                          </div>
                       </div>
                    </div>
                 </div>
              </div>
           </div>
        </div>
     </div>

用于绑定数据的Javascript部分

     var dataset;
     var docsModel;
     var docsTable;
     var vasTypes;
     $(function(){
       var viewModel = {};
       viewModel.fileData = ko.observable({
         dataURL: ko.observable(),
         // base64String: ko.observable(),
       });
       viewModel.onClear = function(fileData){
         if(confirm('Are you sure?')){
           fileData.clear && fileData.clear();
         }                            
       };
       viewModel.debug = function(){
         window.viewModel = viewModel;
         //console.log(ko.toJSON(viewModel));
     fileUpload(viewModel);
         debugger; 
       };
       ko.applyBindings(viewModel);
     });

     $(document).ready(function(){
        docsModel = new $.cordys.model({
              context: document.getElementById("addPanelForm"),
              objectName: "CONTRACT_DOCUMENT",

              fields: ["CONTRACT_DOCUMENT_ID" , "CONTRACT_ID" , "DOCUMENT_NAME" , "FILE_PATH" , "COMMENTS"],
              defaults: {
                 namespace: "http://services.vw.com/lpms/1.0/wsapp"
              },/*
              update: {
                 method: "UpdatePlanVas"
              },*/
              read: {
                 method: "GetContractDocumentObjectsForContractId",
                 parameters: {
                         CONTRACT_ID: "CONTRACT_1000"                           
                         },
              }
        });      

        GetContractDocumentObjectsForContractId();

        docsTable = $('#docsDataTable').DataTable({
           data: dataset,
           columnDefs: [ {
              orderable: false,
              className: 'select-checkbox',
              defaultContent: "",
              targets: 0},
           { data: "CONTRACT_DOCUMENT_ID",
              targets: 1,
              visible: false},
           { data: "CONTRACT_ID",
              targets: 2},

           { data: "DOCUMENT_NAME",
              targets: 3},
                { data: "COMMENTS",
              targets: 5},
           { data: "FILE_PATH",
              targets: 4}],
           select: {
              style:    'multi',
              selector: 'td:first-child'
           },

           order: [[ 1, 'asc' ]],
           "searching": false,
           "lengthChange": false
        });
     });



     function fileUpload(data){
     dataObject=ko.toJS(viewModel);
     fileName=dataObject.fileData.file.name;
     fileContent=dataObject.fileData.dataURL.split(',')[1];
           $.cordys.ajax({
               method: "WriteFile",
     parameters: {
     filename: fileName,
     encoded: "true",
     data:fileContent
     },
               namespace:"http://schemas.cordys.com/1.0/ac/FileConnector",
               dataType: "* json",
               async: false,
               success: function(e){
     $.notify("Yeah ! File Uploaded", "success");

               }
            });
        }

1 个答案:

答案 0 :(得分:1)

您收到错误

  

您无法多次将绑定应用于同一元素

因为Knockout只允许一个视图模型绑定到DOM元素。

在您的情况下,您需要以某种方式将两个视图模型合并为一个。虽然可以只是将属性从一个视图模型添加到另一个视图模型中,但可能会创建一个具有新名称的第三个视图模型,以便您可以继续在其他地方使用这些视图模型的原始形式,建议是创建一个新的 super 视图模型,并将这两个现有的视图模型作为这个新视图模型的属性引用。

此时我通常会在OP中的代码中创建一个示例,但在这种情况下,正如@Jeroen指出的那样,很难弄清楚OP中发生了什么。据我所知,那里只有一个视图模型,而你的问题围绕着两个视图模型。因此,以下示例非常通用。

var ViewModel1 = function() {
    var self = this;
    self.obs1_1 = ko.observable();
    self.obs1_2 = ko.observableArray([]);

    // some initialisation stuff
},
ViewModel2 = function() {
    var self = this;
    self.obs2_1 = ko.observable();
    self.obs2_2 = ko.observableArray([]);

    // some initialisation stuff
},
SuperViewModel = function() {
    var self = this;
    self.vm1 = new ViewModel1();
    self.vm2 = new ViewModel2();

    // some initialisation stuff
};

然后你将实例化和数据绑定SuperViewModel,并引用像这样的observable

<input type="text" data-bind="textInput: vm1.obs1_1" />
<div data-bind="foreach: vm1.obs1_2">
    <span data-bind="html: $data"></span>
</div>

或使打字更容易

<!-- ko with: vm1 -->
    <input type="text" data-bind="textInput: obs1_1" />    <!-- this time without "vm1." -->
    <div data-bind="foreach: obs1_2">                      <!-- this time without "vm1." -->
        <span data-bind="html: $data"></span>
    </div>
<!-- /ko -->

您现在拥有一个视图模型SuperViewModel,引用您未更改的现有视图模型。此解决方案允许您保留现有的JavaScript和视图,同时提供在单个视图模型中对多个视图模型的功能进行数据绑定的简单方法。

技术上可以通过在原型级别进行一些引用来实现类似的结果,但这很快就会导致复杂化,唯一的好处就是可以省去键入属性的名称。