Created
July 26, 2011 16:12
-
-
Save scottmessinger/1107134 to your computer and use it in GitHub Desktop.
Manual subscriptions in Knockout.js
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
// Unit.fetch makes an ajax call and passes new Unit(data) to the callback. | |
Unit.fetch(options, function(unit){ | |
addFunctions(unit) | |
App.VMs.unit(unit) | |
} | |
// the console never logs "subscribed" | |
var addFunctions = function(viewModel){ | |
viewModel.units.subscribe(function(){ | |
console.log("subscribed") | |
var units = this.units(); | |
for (var i = 0, j = units.length; i < j; i++) { | |
var unit = units[i]; | |
if (!unit.index) { | |
unit.index = ko.observable(i); | |
} else { | |
unit.index(i); | |
} | |
} | |
}, viewModel); | |
} | |
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 Unit = function(data){ | |
var _this = this | |
this.root_unit = function(){ | |
return this.id() == App.VMs.course().root_unit_id() | |
} | |
this.show_children = function(){ | |
//console.log(this.nested_children()) | |
return this.nested_children() | |
} | |
var mappings = { | |
'units' : { | |
key: function(item) { | |
return ko.utils.unwrapObservable(item.id); | |
} | |
,create: function(options){ | |
return new Unit(options.data) | |
} | |
} | |
,'contents' : { | |
create : function(options){ | |
return new Content(options.data) | |
} | |
} | |
} | |
this.save = function(){ | |
var data = {} | |
data._timestamp = new Date().getTime(); | |
data.username = App.VMs.course().username() | |
data.id = this.id() | |
data.course_slug = App.VMs.course().slug() | |
data['unit'] = this.toJSON() | |
amplify.request( | |
'unit#update' | |
, data | |
) | |
} | |
this.destroy = function(context){ | |
amplify.request( | |
"unit#delete" | |
,{ | |
username : App.VMs.course().username() | |
,course_slug : App.VMs.course().slug() | |
,id : this.id() | |
} | |
) | |
context.remove(this) | |
} | |
this.addChild = function(){ | |
var _this = this | |
var data = { username : App.VMs.course().username() | |
,course_slug : App.VMs.course().slug() | |
,parent_id : _this.id | |
} | |
data._timestamp = new Date().getTime(); | |
amplify.request( | |
"unit#create" | |
,data | |
,function(data){ | |
data._timestamp = new Date().getTime(); | |
caches.units[data.id] = 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