【问题标题】:knockout with side page causing You cannot apply bindings multiple times to the same element侧页敲除导致您不能多次将绑定应用于同一元素
【发布时间】:2020-05-14 01:33:00
【问题描述】:

我正在使用 knockoutJs 构建一个 SPA。我面临的问题是我有一个带有几个锚链接的侧栏页面,这些链接将根据下面的代码 sn-p 加载不同的页面

 $('div#list a').click(function(){
    var page = $(this).attr('href');
    if (page == "new") {
        $('#container').load('application/application.jsp', function(data){
            //return false;
        });
        return false;
    } else if (page == "dashboard") {
        $('#container').load('dashboard/dashboard.jsp', function(data){
            //return false;
        });
        return false;
    }
 });

对于每个页面,我正在加载相应的 html 和 js。比如上面例子中page是new的,html如下

<form>......fields are there</form><script src="application/application.js"></script>

我的 Js 文件如下:

var ApplicationForm = function () {
/* add members here */
/* the model */
var app = {
    nid: ko.observable(),
    lastName: "",
    firstName: "",
    address: "",
};

var addEmployment = function() {
};

var removeEmployment = function(params) {
};

var init = function () {
    /* add code to initialise this module */
    ko.applyBindings(ApplicationForm);
};

/* form submission */
var submit = function () {
    console.log(ko.toJSON(app ));
};

/**
 * subscribe to checkbox isdead and if false, clear the values
 */
app.isDead.subscribe(function(newValue) {
    //when false, clear all values
     if (!newValue) {
          //
     }
});

/* execute the init function when the DOM is ready */
$(init);

return {
    /* add members that will be exposed publicly */
    submit: submit,
    application: app,
    add: addEmployment,
    remove: removeEmployment
};

}();

省略了一些细节。问题是每次我单击侧链接页面时,它也会加载相应的 JS 和它给出错误 You cannot apply bindings multiple times to the same element,因为我正在调用 applyBindings multiple次。

有人可以建议我如何设计我的页面,以免出现此错误吗?

非常感谢。

【问题讨论】:

  • 我无法从您的代码中看出第二次调用 applyBindings 的位置。是不是每个页面在加载后都会在其init函数中调用它,所以第二次点击链接时就会出现错误?
  • @JasonSake 是的

标签: javascript knockout.js single-page-application knockout-3.0


【解决方案1】:

由于您每次都重复使用相同的元素,因此您需要在应用新的绑定之前清除之前的绑定。这可以通过ko.cleanNode(element); 完成

像这样将它放在切换功能的顶部可能会起作用,但根据发布的可用代码,我无法确定。

$('div#list a').click(function(){
    ko.cleanNode($('#container')[0]);
    ...

您可能还需要将 applyBindings 更改为仅针对同一元素,具体取决于您在该元素之外使用绑定的其他位置。

ko.applyBindings(ApplicationForm, $('#container')[0]);

【讨论】:

  • @ashley 以什么方式不起作用?它可能只需要一点调整
  • @ashley 您是否尝试将您的 applyBindings 更改为也仅适用于容器元素? ko.applyBindings(ApplicationForm, $('#container')[0]);
  • 哇。那行得通。我只是在做 ko.applyBindings(ApplicationForm)。我所做的是正确的还是有更好的方法来构建 html 和 js 文件?非常感谢
  • @ashley 您之前所做的会在全局范围内应用绑定,如果您在容器元素之外还有其他绑定,这可能正是您想要的。这仅取决于其余代码的工作方式。另一种方法可能是全局应用一次绑定,并使用 observables 来交换容器的内容,例如使用模板绑定,但你所拥有的很好
猜你喜欢
  • 2014-01-22
  • 2018-11-22
  • 2017-01-20
  • 2013-09-21
  • 2016-09-26
  • 2018-03-18
  • 2013-07-16
  • 2014-04-13
  • 2017-12-17
相关资源
最近更新 更多