Search code examples
javascriptknockout.jssingle-page-applicationknockout-3.0

knockout with side page causing You cannot apply bindings multiple times to the same element


I am building a SPA using knockoutJs. The problem I am facing is that I have a side bar page with several anchor links which will load different pages as per code snippet below

 $('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;
    }
 });

For each page, I am loading the corresponding html and js. For instance, where page is new in the example above, the html is as follows

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

My Js file is as per below:

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

}();

Some details are omitted. The problem is everytime I click on a side link page, it will load the corresponding and JS as well and it is giving the error You cannot apply bindings multiple times to the same element since I am calling applyBindings multiple times.

Can someone advise me on how I should design my page so that I do not get this error?

Thanks a lot.


Solution

  • Since you're reusing the same element each time you'll need to clear the previous bindings before applying the new ones. This can be done with ko.cleanNode(element);

    It might work to put it at the top of your switching function like so, but I can't tell for sure based on the available code posted.

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

    You might also need to change your applyBindings to only target that same element depending on where else you're using bindings outside of that element.

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