Skip to content

Instantly share code, notes, and snippets.

@Radagaisus
Created November 11, 2012 18:06
Show Gist options
  • Save Radagaisus/4055733 to your computer and use it in GitHub Desktop.
Save Radagaisus/4055733 to your computer and use it in GitHub Desktop.
View
# Mixins
# -------------------------------
# Adapted from The Little Coffee Book
# http://arcturo.github.com/library/coffeescript/03_classes.html
# and this gist:
# https://gist.github.com/993415
moduleKeywords = ['extended', 'included', 'setup']
class Module
@extend: (obj) ->
for key, value of obj when key not in moduleKeywords
@[key] = value
setup() if @setup
@include: (obj) ->
for key, value of obj when key not in moduleKeywords
@::[key] = value
( ($) ->
topics = {}
$.trigger = (topic, o) ->
return this unless topics[topic] and topics[topic].length
subscriber o for subscriber in topics[topic]
this
$.on = (topic, fn) ->
topics[topic] = [] unless topics[topic]
topics[topic].push fn
# Add a dynamic trigger function
unless $[topic]
$[topic] = (o) -> $.trigger topic, o
this
$.off = (topic, fn) ->
# Clear all topics
if not topic and not fn
topics = {}
# Clear a specific topic
else if not fn
topics[topic] = []
# Clear a function
else
# Two functions are equal if they have the same memory address
topics[topic] = (t for t in topics[topic].slice() when t isnt fn)
this
$.bind = $.subscribe = $.on
$.unbind = $.unsubscribe = $.off
)(Events = {})
class View extends Module
@include Events
$$: (el) -> $(@el).find(el)
events: {}
# The constructor builds the access to the parameters received,
# passes them to initialize and delegates the events
constructor: (o) ->
# o - el, template, everything you need to access with 'this' in the view
@$.extend this, o
@initialize(o)
@delegate_events()
# Add event listeners from the @event hash.
delegate_events: ->
# Match the event and the element, separated by space
events = for k,v of @events
k.match(/^(\S+)\s*(.*)$/)[1..2].concat v
for [event, element, fn] in events
do (event, element, fn) =>
_fn = (e) => @[fn](e, @$(e.currentTarget))
# $('.view').on 'click', '.view-header', func
if element
then @$(@el).on event, element, _fn
else @$(@el).on event, _fn
initialize: -> return # placeholder
render: -> @el.html @template @model # default render
release: ->
@trigger 'release', this
@el.remove()
@unbind()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment