Skip to content

Instantly share code, notes, and snippets.

@wulftone
Created December 24, 2011 01:36
Show Gist options
  • Save wulftone/1515885 to your computer and use it in GitHub Desktop.
Save wulftone/1515885 to your computer and use it in GitHub Desktop.
Creating a Backbone.js View Manager
((Account) ->
Account.Route.Registration = Backbone.Router.extend(
routes:
"": "index"
"!/choose": "choose"
initialize: (args) ->
if args.view_managers
_.each args.view_managers, ((view_manager, name) ->
this[name] = view_manager
), this
@customer = new Account.Model.Customer()
@customer_view = new Account.View.Customer(model: @customer)
index: ->
@registered_products = new Account.Collection.RegisteredProducts()
@registered_products_view = new Account.View.RegisteredProducts(collection: @registered_products)
@$account.show
view: @registered_products_view
remove: true
choose: ->
@choose_products = new Account.Collection.ChooseProducts(filter: "Spring 11")
@choose_products_view = new Account.View.ChooseProducts(collection: @choose_products)
@$account.show
view: @choose_products_view
remove: true
)
Account.ViewManager = (options) ->
settings = $.extend(
container: $("#mainContent")
transition: "fade"
speed: 200
, options)
current_view = undefined
transition =
fade: (callback) ->
$(@el).fadeToggle settings.speed
callback.call this if callback
this
normal: (callback) ->
$(@el).toggle settings.speed
callback.call this if callback
this
slide: (callback) ->
$(@el).slideToggle settings.speed
callback.call this if callback
this
Backbone.View::deconstruct = ->
transition[settings.transition].call this, ->
@remove()
@unbind()
@terminate() if @terminate
@show = (options) ->
if options
if options.remove
@remove options.view
else
@hide options.view
@view = options.view if options.view
if @view
settings.container.html transition[settings.transition].call(@view.render()).el
else
alert "No view set."
@hide = ->
transition[settings.transition].call @view if @view
@remove = ->
@view.deconstruct() if @view
Account.Application = new Account.Route.Registration(view_managers:
$account: new Account.ViewManager(container: $("#account"))
)
Backbone.history.start()
) MZW.Account
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment