javascriptcanjscanjs-routing

Defining two separate routers with can.Control.route in CanJS


I have two routes defined in different JS-documents, although both are included into the same HTML-file. Route 1 looks like this:

Router = can.Control({
   "invoices/:id route": function(data){
    //load an invoice by id
   }
 });

And the other one like this:

Router = can.Control({
   "receipts/:id route": function(data){
    //load a receipt by id
   }
 });

When i browse to #!receipts/1 both Receipts and Invoices are being instantiated. Why is that and how can I fix it?


Solution

  • You won't find this in the CanJS docs because it's a basic javascript issue.

    Please note that even though the variables are declared in different scripts, the fact that they are included in the same page means that they both live in the same global namespace, thus the second Control object declaration overwrites the first.

    The simplest answer is to assign each Control object to a different variable (e.g., Router1, Router2).

    You'd also be better off combining both declarations in one file to improve performance.