Navigating in SproutCore

May 10
blog author

dliau

Developer

I've been working with Sproutcore for awhile now. To be honest, it hasn't been a walk in the park. Although, there are great examples and tutorials available if you know where to look. One of the tutorials I found very useful was navigating using routes. Usually, navigating to other panels would consist of getting the current panel, removing it, then appending the new panel. Routes will allow you to encapsulate this process and make it flexible for use throughout a project. First, we will create a new object for the routing logic:

MyApp.routes = SC.Object.create({
   //keep track of the current page
   currentPagePane: null,

  gotoRoute: function(routeParams) {    var pageName = routeParams.pageName;    if (pageName == undefined || pageName == '') {     pageName = 'loginPage';    }
   var paneName = routeParams.paneName;    if (paneName == undefined || paneName == '') {     paneName = 'loginPane';    }
   if (this.currentPagePane != null) {     this.currentPagePane.remove();    }
   var pagePanePath = pageName + '.' + paneName;    var pagePane = MyApp.getPath(pagePanePath);    pagePane.append();
   this.currentPagePane = pagePane;   } });

Here, we are defining the function gotoRoute with 1 parameter (routeParams). This parameter will be used to read in the new panel to navigate to. In the above code, the parameter has 2 properties, pageName and paneName. These are defined when we initialize the route later on and also used as a new path. After extracting the properties (or setting a default) we remove the current pane which is saved in the currentPagePane property. The new path will then be appended and saved as the current pane. Next we need to initialize this route in the main.js file.

SC.routes.add(':pageName/:paneName', MyApp.routes, 'gotoRoute');

This line will register the route using the properties defined in the first parameter. These are the properties from the routeParams variable in the code above. Notice that the first parameter also defines the format of the route similar to a regular URL where each property is prefixed with a ':'. The second parameter defines the object where the logic is and the third defines the function used. Lastly, putting this to good use. To navigate to another page, we simply call:

SC.routes.set('location', 'loginPage/loginPane');

This will set the location to the new value (loginPage/loginPane) and check for any registered routes with this format. Since it matches the format we defined earlier, it will call the gotoRoute function and pass 'loginPage' and 'loginPane' as the 2 properties. Hope this helps. ^.^

Source: Sproutcore: page navigation using routes.