你不能多次申请绑定到相同的元素Knockout.Js

问题描述:

心中已经应用结合只有一次,但仍然得到错误你不能多次申请绑定到相同的元素Knockout.Js

不能多次申请绑定同一个元素。

这是我的脚本。

<script> 
var self = this; 
     var vm = function viewModel() { 
       self.getAppointment = function() { 
        $("#dialog-confirm ").dialog({ 
         resizable: false, 
         height: 250, 
         width: 500, 
         modal: true 
        }); 

        self.checkAppointmentListSelect(true); 
       } 

       self.checkAppointmentListSelect = ko.observable(false); 

       self.btnSelectAppointmentClick = function() { 
        self.checkAppointmentListSelect(true); 
       } 
       debugger; 
      } 

      ko.applyBindings(vm); 
    </script> 

这是HTML数据

<div id="dialog-confirm" title="Select Appointment"> 
     <div class="modal-body" data-bind="visible: checkAppointmentListSelect"> 

      <button class="btn btn-primary" id="btnSelectAppointment" data-bind="click: btnSelectAppointmentClick">Select</button> 
      <button class="btn btn-primary" id="btnCancel">Cancel</button> 
     </div> 

     <div class="modal-body" data-bind="visible: checkAppointmentListSelect"> 

      <button class="btn btn-primary" id="btnSelectAppointment">Select </button> 
      <button class="btn btn-primary" id="btnCancel">Cancel</button> 
     </div> 
    </div> 
+0

此代码工作正常,您可以添加您的视图代码示例?你有更多的地方,你叫ko.applyBindings? –

+0

该页面上正在使用淘汰赛的唯一地点,还是您在两个不同区域使用了两次? –

+0

nope,只在此页 –

几件事情需要注意:

  • var self = this;应在构造函数中。外,this指的是窗口对象。

  • 您应该通过对象包含observable属性到ko.applyBindings()。不是功能本身。

  • 您可以使用Function Expression or Function Declaration在javascript中创建函数。您的代码中的viewModel不是必需的。它可以是 var vm = function() {}function vm(){}

  • 默认情况下,您已将checkAppointmentListSelect设置为false。您的按钮将不会显示在加载*您点击。

你的代码更改为:

function vm() { 
    var self = this; // this should be inside the vm function 

    self.getAppointment = function() { 
    $("#dialog-confirm ").dialog({ 
     resizable: false, 
     height: 250, 
     width: 500, 
     modal: true 
    }); 

    self.checkAppointmentListSelect(true); 
    } 

    self.checkAppointmentListSelect = ko.observable(true); 

    self.btnSelectAppointmentClick = function() { 
    self.checkAppointmentListSelect(true); 
    } 
} 

ko.applyBindings(new vm()); // `new vm()` creates an object of type vm 

Here's a fiddle。如果你仍然面临任何问题,请进行所有这些更改并让我知道。