Skip to content

Instantly share code, notes, and snippets.

@lusentis
Created June 24, 2012 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lusentis/2983090 to your computer and use it in GitHub Desktop.
Save lusentis/2983090 to your computer and use it in GitHub Desktop.
RouterJS - A framework-independent BrowserJS routing and m[vc] lib
###
RouterJS - A framework-independent BrowserJS routing and m[vc] lib
Dependencies: RequreJS for loading, Handlebars for templates, jQuery for ajax and selectors
Part of Plee.co Frontend
(c) 2012 PlasticPanda.com
~ relying solely on what’s been done in the past
is the death of progression ~
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
## RouterJS module file for Require.js
define ['handlebars', 'jquery'], (Handlebars, $) ->
class Router
#conf: {}
models: {}
views: {}
routes: {}
@fixHrefs: (_r) ->
$('a').each (ev) ->
real_href = $(@).attr('href')
return if not real_href
if real_href[0] == '/'
@href = '#!'+real_href
$(@).click (clickev) ->
clickev.preventDefault()
_r.route real_href
return false
init: (@models, @views, @routes) ->
_r = @
$(window).hashchange () ->
Router.fixHrefs _r
Router.fixHrefs _r
route: (loc) ->
for path in @routes
# replacing :identifier with .+ for regexp matching
parts = RegExp(path[0].replace('.', '\\.').replace(/:[a-zA-Z\g]+/g, '(.+)'), 'g').exec(loc)
if parts
window.location?.hash = '!'+loc
parts.splice(0,1) # remove full path
@view path[1], parts
return true
console.error "ERROR 404: Route for `#{loc}` not found."
return false
view: (v, args) ->
callargs = $.extend([
() ->
$(window).hashchange()
], args)
if typeof v == 'object'
# model and function name
@models[v[0]][v[1]].apply(undefined, callargs)
return true
else if typeof v == 'function'
v.apply(undefined, callargs)
return true
else if typeof v == 'string'
@views[v].apply(undefined,callargs)
return true
console.error "ERROR 500: View does not exist."
return false
"""
SyncModel base class
-------------------------
Defines a models that abstracts a remote REST API.
"""
class SyncModel
constructor: (options) ->
# getter/setter for model fields - jQ style :)
attr: (name, value) =>
@_fields = {} if not @_fields
if value
@_fields[name] = value
else
return @_fields[name]
_do_request: (urlSuffix, method, data, callback) ->
$.ajax({
url: @url + urlSuffix ? ''
type: method
data: _.extend(data, @extra_data)
}).done (resp) ->
callback(resp) if callback.call?
@render_template: (template, context) ->
#console.log 'Rendering template ', template, ' with context ', context
return Handlebars.compile(template)(context)
formHandler: (t, callback) ->
obj = @
console.log 'obj has id ', obj.attr('_id')
$(t).find(':input[data-model="true"]').each (index, item) ->
return if not item.name
console.log 'adding ', item.name
obj.attr item.name, $(item).val()
console.log 'calling with _id ', obj.attr('_id')
obj.save obj.attr('_id'), (resp) ->
callback(resp) if callback?
return false
get: (to_element, _id, callback) ->
@_do_request _id || '', 'GET', {}, (resp) =>
if resp?.error
console.error 'API server returned error code.', resp
else
#console.log resp
template_data = resp
@attr('_id', resp._id)
to_element?.html SyncModel.render_template(@template, template_data)
callback(resp.error||true) if callback?
return to_element
save: (_id, callback) ->
throw new Error('Cowardly refusing to save an empty object.') if not @_fields or @_fields=={}
if not _id? and @attr('_id')?
_id = @attr('_id')
if not _id?
callType = 'POST' # create
else
callType = 'PUT' # update
@_do_request _id || '', callType, @_fields, (resp) ->
callback(resp) if callback?
delete: (_id, callback) ->
@_do_request _id || '', 'DELETE', {}, (resp) ->
callback(resp) if callback?
refreshView = () ->
alert 'DEBUG: refreshView() is not supported.' # DEBUG:
#window.router.route window.location.hash.replace('#!', '')
return {
refreshView: refreshView
Router: Router
SyncModel: SyncModel
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment