我正在使用 knockoutJs 构建 SPA。我面临的问题是我有一个带有多个 anchor 链接的侧栏页面,这些链接将根据下面的代码片段加载不同的页面
$('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。例如上面例子中的页面是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 和 JS,并且给出错误 You can not apply bindings multiple times to the same element 因为我多次调用 applyBindings次。
有人可以建议我如何设计我的页面,这样我就不会收到此错误吗?
非常感谢。
最佳答案
由于您每次都重复使用相同的元素,因此您需要在应用新的绑定(bind)之前清除以前的绑定(bind)。这可以通过 ko.cleanNode(element);
来完成
像这样将它放在切换函数的顶部可能会起作用,但我无法根据发布的可用代码确定。
$('div#list a').click(function(){
ko.cleanNode($('#container')[0]);
...
您可能还需要将 applyBindings 更改为仅针对同一元素,具体取决于您在该元素之外的其他位置使用绑定(bind)。
ko.applyBindings(ApplicationForm, $('#container')[0]);
关于javascript - 侧页 knockout 导致您无法将绑定(bind)多次应用于同一元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59952073/