Skip to content

Instantly share code, notes, and snippets.

@pongo
Created March 12, 2015 22:48
Show Gist options
  • Select an option

  • Save pongo/b50259ed6420f2cdabf8 to your computer and use it in GitHub Desktop.

Select an option

Save pongo/b50259ed6420f2cdabf8 to your computer and use it in GitHub Desktop.
How to create a simple --JavaScript-- CoffeeScript library in jQuery style. Based on http://bjarneo.codes/how-to-create-a-simple-javascript-library-like-jquery/
# Anonymous function
do ->
# Q returns new Library object that hold our selector. Ex: Q('.wrapper')
Q = (params) ->
new Library(params)
# In our Library we get our selector with querySelectorAll (we do not support < ie8)
# We also add selector length, version and twitter/github or whatever you like as information about your library.
Library = (params) ->
# Get params
selector = document.querySelectorAll(params)
i = 0
# Get selector length
@length = selector.length
@version = '0.1.0'
@twitter = 'http://www.twitter.com/bjarneo_'
# Add selector to object for method chaining
while i < @length
@[i] = selector[i]
i++
# Return as object
this
# Extend the Library object.
Q.fn = Library:: =
# Hide element(s) from DOM
# @returns {*}
hide: ->
len = @length
# Here we simply loop through our object (this) and set the css to display none.
#If you got more that 1 node from DOM selected with querySelectorAll, you would hide them all.
while len--
@[len].style.display = 'none'
# It's important to return this if you want to chain methods!
this
# Show element(s) from DOM
# @returns {*}
show: ->
len = @length
while len--
@[len].style.display = 'block'
this
# Assign our Q object to global window object.
window.Q = Q unless window.Q
return
# Example usage:
Q '.wrapper'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment