Skip to content

Instantly share code, notes, and snippets.

@scottmessinger
Created July 27, 2011 17:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottmessinger/1109917 to your computer and use it in GitHub Desktop.
Save scottmessinger/1109917 to your computer and use it in GitHub Desktop.
Common Curriculum Knockout.js Walkthrough
// index.haml
$(function() {
App.init();
});
//application.js
var App = {
VMs : {
global : {
mainTemplate : ko.observable()
}
,unit : ko.observable()
,course : ko.observable()
,user : ko.observable()
,current_user : ko.observable()
}
,trackers : {}
,init: function() {
new App.Router();
Backbone.history.start();
ko.applyBindings(App.VMs)
addFunctions(App.VMs.unit)
ko.applyBindings(App.trackers, 'dirty')
}
}
// ROUTER
App.Router = Backbone.Router.extend({
routes : {
,"!/:username" : "show_user"
,"!/:username/:course_slug": "show_course"
,"!/:username/:course_slug/:unit_id": "show_unit"
}
,show_unit: function(username, course_slug, id){
$("#loading").fadeIn(100)
Course.fetch(username, course_slug, function(course){
App.VMs.course(course)
Unit.fetch({/* params */}, function(unit){
addFunctions(unit) // dependent observables
App.VMs.unit(unit)
addTrackers(App.trackers)
App.VMs.global.mainTemplate('show_course')
$("#loading").fadeOut()
})
})
}
})
Unit.fetch = function(data, cb){
$.ajax(
{ /* params */}
,function(data){
var unit = new Unit(data)
cb(unit)
}
)
}
var Unit = function(data, parent){
var mappings = {
'units' : {
key: function(item) {
return ko.utils.unwrapObservable(item.id);
}
,create: function(options){
return new Unit(options.data, _this)
}
}
,'contents' : {
create : function(options){
return new Content(options.data, _this)
}
}
}
this.save = function(){
// AJAX REQUEST!!!
}
this.destroy = function(context){
// AJAX REQUEST!
context.remove(this)
}
this.addChild = function(){
$.ajax(
{ /* params */ }
,function(data){
unit = new Unit(data)
_this.units.push(unit)
}
)
}
ko.mapping.fromJS(data, mappings, _this)
this.dirtyFlag = new ko.dirtyFlag(_this, false)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment