Last active
January 4, 2016 21:29
-
-
Save DavidBennettPIO/8681606 to your computer and use it in GitHub Desktop.
Can.js Route View Controler helper plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
can.routeVC = can.Construct.extend('can.routeVC', { | |
routerControl:null, | |
view_dir: 'views/', | |
view_ext: can.view.ext, | |
data: {} | |
},{ | |
init: function(attachTo, routes){ | |
var self = this; | |
var route_config = {} | |
if(routes.hasOwnProperty('init')) | |
{ | |
route_config['init'] = routes.init; | |
delete routes.init; | |
} | |
var route_render = function(config){ | |
var render = function(data){ | |
self.constructor.data = data; | |
$( attachTo ).html( | |
can.view( | |
self.constructor.view_dir+config.view+self.constructor.view_ext, | |
self.constructor.data | |
) | |
); | |
} | |
return function(params){ | |
if(config.hasOwnProperty('action')) | |
{ | |
var control = new config.control(); | |
control[config.action](params, render); | |
}else{ | |
new config.control(params, render); | |
} | |
} | |
} | |
can.each(routes, function(config, route){ | |
if(!config.hasOwnProperty('view')) | |
{ | |
if(config.hasOwnProperty('action')) | |
{ | |
config.view = config.action; | |
}else{ | |
config.view = 'index'; | |
} | |
} | |
route_config[route] = route_render(config); | |
}) | |
var RouterControl = can.Control.extend(route_config); | |
self.constructor.routerControl = new RouterControl(window); | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Todo = can.Model({ | |
findAll : 'GET /todos', | |
findOne : 'GET /todos/{id}', | |
create : 'POST /todos', | |
update : 'PATCH /todos/{id}', | |
destroy : 'DELETE /todos/{id}' | |
},{}) | |
var TodosControl = can.Control.extend({ | |
init: function() { | |
console.log("init Todos"); | |
}, | |
index: function( params, render ) { | |
can.when(Todo.findAll()).then(function(todos){ | |
render({todos:todos}); | |
}); | |
}, | |
show: function( params, render ) { | |
can.when(Todo.findOne(params['id'])).then(function(todo){ | |
render({todo:todo}); | |
}); | |
} | |
}); | |
new can.routeVC('#view', | |
{ | |
"todos route": { | |
control: TodosControl, | |
action: 'index' | |
}, | |
"todos/:id route" : { | |
control: TodosControl, | |
action: 'show' | |
} | |
}); | |
can.route.ready() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment