Some caveats beforehand:
I'm using RequireJS to divide my app up into modules - this isn't necessarily required (no pun intended) - you could just dump everything in one Javascript file and have it work, I just find it easier to organize and work with. This question shows how my project is laid out.
I'm also not using SammyJS for routing, but Crossroads and Hasher. The concepts should be somewhat the same though.
The examples below probably aren't a 100% match for what you're doing, but hopefully it gives you an idea of the approach I'm using.
My main.js
contains all the routing info, and inside each route handler, I use require()
from RequireJS to pull in the module(s) I'm using for that route. Each module contains the Knockout ViewModel and several methods to do things like load data for the ViewModel, bind it in certain contexts, etc.
main.js
here's how I handle the route to show the #/person/id
route:
crossroads.addRoute("person/{id}", function(id){
require(["person"], function(person) {
var model = person.load(id);
person.view($('#content'), model);
});
});
Significant parts of person.js
:
define(['jquery', 'knockout', ...], function($, ko, ...) {
var person = {};
person.Model = function Model(id) {
this.id = ko.observable(id);
this.name = ko.observable();
// more properties and methods removed...
};
person.load = function(id) {
var model = new person.Model(id);
var request = $.ajax({
// ajax config properties removed...
'success' : function(resp) {
model.name (resp.name);
// more property setting removed...
}
});
return model;
};
person.view = function(element, model) {
// Using require text plugin to load templates...
require(['text!templates/person/view.tmpl.html'], function(ViewTemplate) {
element.empty();
element.html(ViewTemplate).ready(function() {
ko.applyBindings(model, element.get(0));
// any further setup needed below...
});
});
};
return person;
});