js.mv.Engine.js Maven / Gradle / Ivy
The newest version!
define(function(require){
var $ = require("jquery"),
crossroads = require("crossroads"),
mvrenderer = require("./Renderer"),
windowEl = $(window);
return function(cfg){
cfg = $.extend({
pages: {"": function(){ this.html = "No Pages specified!"; } },
target: $("#content")
}, cfg);
var containers = {},
self = this,
c = crossroads.create(),
i = 0,
currentContainer;
var routeModel = function(route, model){
var tabClass = "tab" + i++;
cfg.target.append("");
var el = cfg.target.find("." + tabClass);
c.addRoute(route, function(){
if (currentContainer){
//Save scroll position
currentContainer.scroll = windowEl.scrollTop();
//hide current container
currentContainer.el.hide();
if (typeof(currentContainer.model.hide) === "function")
currentContainer.model.hide();
}
if (typeof(containers[route]) === "undefined"){
//route was never rendered before
//Create instance if function given
if (typeof(model) === "function")
model = new model();
//Create route instance
containers[route] = {
el: el,
scroll: 0,
model: model
};
//Render page
mvrenderer(model, el);
}
var container = containers[route];
//Show new container
container.el.show();
//Restore scroll position
windowEl.scrollTop(container.scroll);
//Apply matched arguments
if (typeof(container.model.matched) === "function")
container.model.matched.apply(container.model, arguments);
if (typeof(container.model.show) === "function")
container.model.show();
currentContainer = container;
});
};
//Route all models/pages
for (var route in cfg.pages)
routeModel(route, cfg.pages[route]);
//Routes to the given location
this.route = function(location){
c.parse(location);
};
this.start = function(){
var hashChange = function(){
self.route(location.hash.substring(1));
};
//Listen to hashchange
windowEl.on("hashchange", hashChange);
//initialize engine
hashChange();
};
};
});
© 2015 - 2025 Weber Informatics LLC | Privacy Policy