Created
January 27, 2012 00:01
-
-
Save boundvariable/1685985 to your computer and use it in GitHub Desktop.
Chapter 5 example
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
class Server | |
@http = (method, src, callback) -> | |
handler = -> | |
if @readyState is 4 and @status is 200 | |
unless @responseText is null | |
callback JSON.parse @responseText | |
client = new XMLHttpRequest | |
client.onreadystatechange = handler | |
client.open method, src | |
client.send() | |
@get = (src, callback) -> | |
http "GET", src, callback | |
@post = (src, callback) -> | |
http "POST", src, callback | |
class Mixin | |
@:: = null | |
constructor: (to) -> | |
for key, val of @ | |
to[key] = val | |
class View extends Mixin | |
constructor: (to) -> | |
super | |
@node = document.createElement 'div' | |
@node.className = "product" | |
document.body.appendChild @node | |
template = (fn) -> | |
@template = fn | |
handler: (event, fn) -> | |
@node[event] = fn() | |
update: -> | |
@node.innerHTML = @template() | |
class Product | |
products = [] | |
@find = (query) -> | |
(product for product in products when product.name is query) | |
constructor: (@name, @info) -> | |
products.push @ | |
@view = new View @ | |
@view.template = => | |
display_info = "<div>#{key}: #{val}</div>" for own key, val of @info | |
"#{@name} #{display_info}" | |
@view.render() | |
@view.handler "onclick", @purchase | |
purchase: => | |
if @info.stock > 0 | |
Server.post "/json/purchase/#{@purchase_category}/#{@name}", (res) => | |
if res.status is "success" | |
@info = res.update | |
@view.render() | |
class Camera extends Product | |
purchase_category: 'camera' | |
megapixels: -> @info.megapixels || "Unknown" | |
class Skateboard extends Product | |
purchase_category: 'skateboard' | |
length: -> @info.length || "Unknown" | |
class Shop | |
constructor: -> | |
@view = document.createElement "input" | |
@view.type = "text" | |
@view.value = "" | |
@view.onchange = -> | |
console.log Product.find @value | |
document.body.appendChild @view | |
Server.get '/json/list', (data) -> | |
for own category of data | |
for own name, info of data[category] | |
switch category | |
when 'camera' | |
new Camera name, info | |
when 'skateboard' | |
new Skateboard name, info | |
shop = new Shop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment