【发布时间】: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