Search code examples
javascriptcanjscanjs-routing

Button being called multiple times


I have a search page and an edit page. I search for a user and then when I get the results, I'm able to edit the user. I'm using CanJS and I've defined routes for each page.

, 'search route': function (data) {
    new FormUserQuery('#formArea', {});
    }
}
, 'edit/:id route': function (data) {
    new FormUser('#formArea', {}).renderView(+data.id);
    }
}

In FormUser I have a click event for the saveButton. If I search a user and then press the edit button, change something and save the changes, it works fine. But if, after saving, I go back to the search page and do the same things as I did before, the save button is being called twice. I have no idea why this is happenning. What am I doing wrong?

Edit I made it work. Whenever I clicked on a new edit button, somehow the view was being placed on top of another, it wasn't replacing the old one.

So I tried this and it worked:

, 'search route': function (data) {
   if (typeof self.form === 'undefined')
   {
    self.form = new MegaControl.FormUserQuery('#formArea', {});
   }
   else {
    self.form.destroy();
    self.form = new MegaControl.FormUserQuery('#formArea', {});
   }

}
, 'edit/:id route': function (data) {
 if (typeof self.form === 'undefined') {
  self.form = new MegaControl.FormUser('#formArea', {})
  self.form.renderView(+data.id);
 }
 else {
  self.form.destroy();
  self.form = new MegaControl.FormUser('#formArea', {});
  self.form.renderView(+data.id);
 }
}

Solution

  • You shouldn't need to call destroy manually as you are doing. The issue is that you are using the same DOM element for both views (#formArea).

    Can will call destroy automatically for you when an element is removed from the DOM, so that is the step that is missing.

    So maybe instead of reusing the same element, you could append an element first and pass that newly created element to the control. Something like:

    'search route': function (data) {
        $('#formArea').empty(); // this will remove previous elements and trigger destroy automatically
        var view = $('<div>'); 
        $('#formArea').append(view); 
        new FormUserQuery(view, {});
    }