Created
November 18, 2011 12:04
-
-
Save sbellity/1376278 to your computer and use it in GitHub Desktop.
Base ViewModel Class for knockback ?
This file contains hidden or 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
class BaseViewModel | |
constructor: (model, opts)-> | |
@model = model | |
mapping = {} | |
@collections = {} | |
for k,v of model.attributes | |
if v instanceof Backbone.Collection | |
@[k] = ko.observableArray([]) | |
vm_name = opts.viewModelName || k.singularize().camelize() + "ViewModel" | |
vm = exports.ViewModels[vm_name] || exports.ViewModels.BaseViewModel | |
@collections[k] = kb.collectionObservable(v, @[k], { view_model: vm }, this) | |
else | |
mapping[k] = { key: k } | |
@observables = kb.observables(model, mapping, this) | |
@initialize.call(this, arguments...) if _.isFunction(@initialize) | |
this | |
destroy: -> | |
console.warn("Calling destroy on vm !", this) | |
@observables.destroy() | |
col.destroy() for k, col of @collections | |
exports.ViewModels.BaseViewModel = BaseViewModel |
This file contains hidden or 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
class ClientViewModel extends exports.ViewModels.BaseViewModel | |
initialize: -> | |
console.warn("using ClientViewModel") | |
exports.ViewModels.ClientViewModel = ClientViewModel | |
class ProjectViewModel extends exports.ViewModels.BaseViewModel | |
initialize: -> | |
console.warn("Using ProjectViewModel...") | |
sayHello: -> | |
console.warn("Hello, #{@model.get('title')}", @model.get('default_image')) | |
exports.ViewModels.ProjectViewModel = ProjectViewModel | |
KnockoutTestView = Backbone.View.extend | |
templateName: "knockout-test" | |
initialize: (opts)-> | |
@parent_view = opts.parent_view | |
@parent_el = opts.parent_el | |
@parent_el ?= @parent_view.el if @parent_view | |
@viewModel = new exports.ViewModels.ClientViewModel(@model) | |
render: (tpl_name)-> | |
$(@parent_el).append($(@el)) | |
$(@el).html(template(@templateName, this)) | |
this | |
exports.Views.KnockoutTestView = KnockoutTestView |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment