【问题标题】:You cannot apply bindings multiple times to the same element in Knockout.Js您不能多次将绑定应用于 Knockout.Js 中的同一元素
【发布时间】:2018-03-18 02:07:21
【问题描述】:

我只应用了一次绑定,但仍然出现错误

您不能对同一个元素多次应用绑定。

这是我的脚本。

    <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>

【问题讨论】:

  • 这段代码运行良好,您可以添加您的视图的代码示例吗?你有更多的地方调用 ko.applyBindings 吗?
  • 是该页面上唯一使用淘汰赛的地方,还是您在两个不同的区域使用了两次?
  • 不,仅在此页面中
  • 在您的问题之外的某个地方发生了其他事情。我注意到这是一个对话框 - 这可能是动态加载的,它可能在第二次和后续尝试中失败?否则,我们无法从您发布的内容中继续前进。
  • 还有几点:您的代码中的var self = this; 在VM 之外,很难从您的帖子中看出,但它可能是window 对象。您不应该将您的 VM 道具分配给它。而是创建一个单独的对象。

标签: javascript jquery knockout.js


【解决方案1】:

有几点需要注意:

  • 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。进行所有这些更改,如果您仍然遇到任何问题,请告诉我。

【讨论】:

    猜你喜欢
    • 2013-07-16
    • 2014-01-22
    • 2017-01-20
    • 2013-09-21
    • 2016-09-26
    • 2018-11-22
    • 2014-04-13
    • 2017-12-17
    • 2016-10-13
    相关资源
    最近更新 更多