public
Last active — forked from maccman/spine.coffee

  • Download Gist
spine.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
# In general, there are many places in the file where you can leave off the parens in function calls, if you like.
 
unless typeof exports is "undefined" # `unless ... else` reads poorly in English. Better to stick to `if ... else`.
Spine = exports
else
Spine = @Spine = {}
Spine.version = "0.0.4"
$ = Spine.$ = @jQuery || @Zepto || -> arguments[0] # In Coffee, `or` is preferred over `||`.
 
makeArray = Spine.makeArray = (args) ->
Array.prototype.slice.call(args, 0) # A shortcut for prototype accessors is: `::` `Array::slice` will do.
isArray = Spine.isArray = (value) ->
Object.prototype.toString.call(value) == "[object Array]" # Ditto. `Object::toString`
Events = Spine.Events =
bind: (ev, callback) ->
evs = ev.split(" ")
calls = @_callbacks || @_callbacks = {}
for name in evs
@_callbacks[name] ?= [] # `or=` here would be more efficient, if it matters.
@_callbacks[name].push(callback)
@
 
trigger: (args...) ->
ev = args.shift()
list = @_callbacks?[ev]
return false unless list
for callback in list
if callback.apply(this, args) is false
break
true
 
unbind: (ev, callback) ->
unless ev
@_callbacks = {}
return @
list = @_callbacks?[ev]
return @ unless list
unless callback
delete @_callbacks[ev]
return @
 
for cb, i in list # You can use `when` to filter a comp. `for cb, i in list when cb is callback`
if callback == cb
list.splice(i, 1)
break
@
 
Log = Spine.Log =
trace: true
 
logPrefix: "(App)"
 
log: (args...) ->
return unless @trace
return if typeof console == "undefined" # In Coffee, prefer `is` to `==`.
if @logPrefix then args.unshift(@logPrefix)
console.log.apply(console, args)
@
# Classes (or prototypial inheritors)
unless typeof Object.create is "function" # This faux Object.create is not API compatible with the real thing, so be careful.
Object.create = (o) ->
F = ->
F.prototype = o
new F()
moduleKeywords = ["included", "extended"]
 
Class = Spine.Class =
inherited: ->
created: ->
prototype:
initialize: ->
init: ->
 
create: (include, extend) ->
object = Object.create(@)
object.parent = @
object:: = object.fn = Object.create(@::)
 
object.include(include) if include
object.extend(extend) if extend
 
object.created()
@inherited(object)
object
 
init: ->
instance = Object.create(@::)
instance.parent = @
 
instance.initialize.apply(instance, arguments)
instance.init.apply(instance, arguments)
instance
 
proxy: (func) ->
=> func.apply(this, arguments)
proxyAll: (names...) ->
@[name] = @proxy(@[name]) for name in names
 
include: (obj) ->
for key, value of obj # Again, you can use a `when` if you like.
unless key in moduleKeywords
@::[key] = value
 
included = obj.included
included.apply(this) if included
@
 
extend: (obj) ->
for key, value of obj
unless key in moduleKeywords
@[key] = value
extended = obj.extended
extended.apply(this) if extended
@
Class::proxy = Class.proxy
Class::proxyAll = Class.proxyAll
Class.inst = Class.init
Class.sub = Class.create
 
Spine.guid = `function(){
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
}).toUpperCase();
}` # This shouldn't need to be backtick'd. No?
 
Model = Spine.Model = Class.create()
Model.extend(Events)
 
Model.extend
setup: (name, atts) ->
model = Model.sub()
model.name = name if name
model.attributes = atts if atts
model
created: (sub) ->
@records = {}
if @attributes then makeArray(@attributes) # Multi-line if/elses should probably use indentation.
else @attributes = []
 
find: (id) ->
record = @records[id]
throw("Unknown record") unless record
record.clone()
 
exists: (id) ->
try
return @find(id)
catch e
return false
 
refresh: (values) ->
values = @fromJSON(values)
@records = {}
 
for record in values
record.newRecord = false
@records[record.id] = record
@trigger("refresh")
@
 
select: (callback) ->
result = (record for id, record of @records when callback(record))
@cloneArray(result)
 
findByAttribute: (name, value) ->
for id, record of @records
if record[name] == value
return record.clone()
null
 
findAllByAttribute: (name, value) ->
@select (item) ->
item[name] == value
 
each: (callback) ->
for key, value of @records
callback(value)
 
all: ->
@cloneArray(@recordsValues())
 
first: ->
record = @recordsValues()[0]
record?.clone()
 
last: ->
values = @recordsValues()
record = values[values.length - 1]
record?.clone()
 
count: ->
@recordsValues().length
 
deleteAll: ->
for key, value of @records
delete @records[key]
 
destroyAll: () -> # Functions that take no arguments require no parens before the arrow.
for key, value of @records
@records[key].destroy()
 
update: (id, atts) ->
@find(id).updateAttributes(atts)
 
create: (atts) ->
record = @init(atts)
record.save()
 
destroy: (id) ->
@find(id).destroy()
 
sync: (callback) ->
@bind("change", callback)
 
fetch: (callbackOrParams) ->
if typeof(callbackOrParams) == "function"
@bind("fetch", callbackOrParams)
else
@trigger("fetch", callbackOrParams)
 
toJSON: ->
@recordsValues()
fromJSON: (objects) ->
return unless objects
if typeof objects == "string"
objects = JSON.parse(objects)
if isArray(objects)
return (@init(value) for value in objects)
else
@init(objects)
 
# Private
 
recordsValues: ->
result = []
for key, value of @records
result.push(value)
result
 
cloneArray: (array) ->
result = []
result.push value.clone() for value in array
result
 
Model.include
model: true
newRecord: true
 
init: (atts) ->
@load atts if atts
@trigger("init", this)
 
isNew: () ->
@newRecord
isValid: () ->
not @validate()
 
validate: ->
 
load: (atts) ->
for key, value of atts
@[key] = value
 
attributes: ->
result = {}
result[key] = @[key] for key in @parent.attributes
result.id = @id
result
 
eql: (rec) ->
rec && rec.id == @id && rec.parent == @parent
 
save: ->
error = @validate()
if error
@trigger("error", @, error)
return false
@trigger("beforeSave", @)
if @newRecord then @create() else @update()
@trigger("save", @)
return @
 
updateAttribute: (name, value) ->
@[name] = value
@save()
 
updateAttributes: (atts) ->
@load(atts)
@save()
destroy: ->
@trigger("beforeDestroy", @)
delete @parent.records[@id]
@destroyed = true
@trigger("destroy", @)
@trigger("change", @, "destroy")
 
dup: ->
result = @parent.init(@attributes())
result.newRecord = @newRecord
result
clone: ->
Object.create(@)
 
reload: ->
return @ if @newRecord
original = @parent.find(@id)
@load(original.attributes())
return original
 
toJSON: ->
@attributes()
exists: ->
@id && @id of @parent.records # Prefer `and` to `&&`.
 
# Private
 
update: ->
@trigger("beforeUpdate", @)
records = @parent.records
records[@id].load @attributes()
clone = records[@id].clone()
@trigger("update", clone)
@trigger("change", clone, "update")
 
create: ->
@trigger("beforeCreate", @)
@id = Spine.guid() unless @id
@newRecord = false
records = @parent.records
records[@id] = @dup()
clone = records[@id].clone()
@trigger("create", clone)
@trigger("change", clone, "create")
bind: (events, callback) ->
@parent.bind events, (record) =>
if record && @eql(record)
callback.apply(@, arguments)
trigger: ->
@parent.trigger.apply(@parent, arguments)
# Controllers
eventSplitter = /^(\w+)\s*(.*)$/
 
Controller = Spine.Controller = Class.create
tag: "div"
initialize: (options) ->
@options = options
 
for key, value of @options
@[key] = value
 
@el = document.createElement(@tag) unless @el
@el = $(@el)
 
@events = @parent.events unless @events
@elements = @parent.elements unless @elements
 
@delegateEvents() if @events
@refreshElements() if @elements
@proxyAll.apply(@, @proxied) if @proxied
$: (selector) ->
$(selector, @el)
delegateEvents: ->
for key of @events
methodName = @events[key]
method = @proxy(@[methodName])
match = key.match(eventSplitter)
eventName = match[1]
selector = match[2]
 
if selector == ''
@el.bind(eventName, method)
else
@el.delegate(selector, eventName, method)
refreshElements: ->
for key, value of @elements
@[value] = @$(key)
delay: (func, timeout) ->
setTimeout(@proxy(func), timeout || 0)
 
Controller.include(Events)
Controller.include(Log)
 
Spine.App = Class.create()
Spine.App.extend(Events)
 
Controller.fn.App = Spine.App

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.