layout | title | permalink |
---|---|---|
default |
API Reference (v0.3.9) |
/reference/index.html |
require 'zappajs'
returns a function with the following attributes:
Version of zappa running. If you're running a version not released on npm (directly from the repo), it will have -edge
appended to it. Ex.: 0.3.0-edge
.
zappa.app [locals,] function
Builds an app with express/socket.io, based on the function you provided.
This function will be called with the value of this
/@
set to an object with all the attributes described in the root scope section.
Returns an object with attributes id
(uuid generated by zappa for this app), app
(express server) and io
(socket.io server).
zappa.run [port,] [host,] [options,] function
Same as zappa.app
, but calls app.listen
for you.
The base export is actually a reference to this same function, so these are equivalent:
require('zappajs').run ->
@get '/': 'hi'
require('zappajs') ->
@get '/': 'hi'
You can pass the parameters in any order. Number is port, string is host, object is options, and function is your application. Port and host are optional. Omitted params will also be omitted in the app.listen
call to express (defaulting to port 3000 and binding to INADDR_ANY
).
You can also pass the parameters in the options
object. The following options are available:
-
port
-
host
-
disable_io
: if true, the Socket.IO interface will be disabled. -
css
: an array of CSS template modules names, or a string containing a single CSS template module name. Defaults to["stylus"]
.require('zappajs') css:'less', -> @less '/index.css': 'body { color: black }'
-
https
: object containing options for HTTPS. Generallykey
andcert
are all you need:# Start a HTTPS server on port 3443 require('zappajs') 3443, https:{ key: ... , cert: ... }, -> @get '/': 'hi'
It will automatically print the equivalent to the following to stdout:
Express server listening on port xxxx in [development/production] mode
Zappa x.x.x orchestrating the show
Creates a zappa view adapter to be used with @register
. See @view
.
The function you pass to zappa.app
or zappa.run
will be called with this
/@
set to an object with the following attributes:
@get '/path': handler
@get '/path', middleware, ..., handler
Define handlers for HTTP requests.
Shortcuts to express' app.[verb]
. Params will just be passed forward unmodified (except for the middleware and handler functions, which will be re-scoped), unless a single object is passed. In which case, each key in the object will be a route path, and the value its respective handler. The handler can be a function or a string. In the latter case, the handler passed to express will be a function that only calls res.send
with this string.
The handler and middleware functions will have access to all variables described in the HTTP handlers scope section.
If a handler returns a string, res.send(string)
will be called automatically.
Ex.:
@get '/': 'hi'
@get '/', -> 'hi'
@get /regex/, -> 'hi'
@get '/': 'hi', '/wiki': 'wiki', '/chat': 'chat'
@get
'/': -> 'hi'
'/wiki': 'wiki'
'/chat': -> response.send 'chat'
# Route Middleware example
load_user = ->
user = users[@params.id]
if user
@request.user = user
@next()
else
@next "Failed to load user #{@params.id}"
@get '/', load_user, -> 'hi'
@on event: handler
Define handlers for events emitted by the client through socket.io.
Shortcut to socket.io's socket.on 'event'
.
The handler functions will have access to all variables described in the Socket.io handlers scope section. They won't have access to their parent scope. To make variables available to these handlers, use helper
.
@helper name: data
The helper will provide the associated data.
@helper name: function
A function that will be available to both the HTTP and sockets scopes. It will have access to the same variables as whatever called it. Ex.:
@get '/': ->
@sum 5, 7
@on connection: ->
@sum 26, 18
@helper sum: (a, b) ->
# Values when called from `@get` vs `@on`
console.log a # 5 vs 26
console.log @request # available vs undefined
console.log @emit # undefined vs available
Since the parameter is actually an object, you can define any number of helpers in one go:
@helper
sum: (a, b) -> a + b
subtract: (a, b) -> a - b
@view path: contents
Define an inline template. For all purposes it's like you had a file on disk at path
. It will have precedence over a template on disk.
Ex.:
@view index: ->
h1 @foo
@view 'index.eco': '''
<h1><%= @foo %></h1>
'''
By default, the templating engine is CoffeeCup. To use other engines, just use express' mechanisms:
@render 'index.jade'
Or:
@set 'view engine': 'jade'
All variables at @
/params
(request params + those you created) are automatically made available to templates as params.foo
(in CoffeeCup, @params.foo
).
In addition, if you're using the zappa view adapter (as is the case by default, with CoffeeCup), they're also made available at the template's "root namespace" (foo
or CoffeeCup's @foo
).
Since in express templating data is usually mixed up with framework locals and template options, the adapter will only put variables in the template root if there isn't a variable there with the same name already, and the name is not blacklisted.
To use this feature with other templating engines:
blacklist = 'scope self locals filename debug compiler compileDebug inline'.split ' '
@register jade: @zappa.adapter 'jade', blacklist
To disable it on default zappa:
@register coffee: require('coffeekup').adapters.express
@postrender name: function
DOM rendering with server-side jQuery. Defines a function that can be applied after @render
.
To use this feature, npm install jsdom
first.
@postrender plans: ($) ->
$('.staff').remove() if @user.plan isnt 'staff'
$('div.' + @user.plan).addClass 'highlighted'
@get '/postrender': ->
@user = plan: 'staff'
@render index: {postrender: 'plans'}
It receives an alternative reference to the context as an optional last parameter:
@postrender plans: ($, foo) ->
$('.staff').remove() if foo.user.plan isnt 'staff'
@include file
Will require
the file at the path specified, and run a function exported as include
against the same scope as the current function. Ex.:
# app.coffee
require('zappajs') ->
@foo = 'bar'
ping = 'pong'
@get '/': 'main'
@include './sub'
# sub.coffee
@include = ->
console.log @foo # 'bar'
console.log ping # error
get '/sub': 'sub'
@include require "module"
Allows to require
arbitrary modules (using the standard Node.js algorithm). The module must export a function include
.
@client '/foo.js': ->
sum = (a, b) -> a + b
@helper foo: (param) ->
console.log param # 'bar' or 'pong'
sum 1, 2 # 3
console.log @zig # A request or event input param.
if @render? then console.log 'route'
else if @emit? then console.log 'event'
@get '#/': ->
@foo 'bar'
console.log 'A client-side route.'
@on welcome: ->
@foo 'pong'
console.log 'A socket.io event.'
Serves ";zappa.run(#{your_function});"
as /foo.js
, with content-type application/javascript
.
To use it, you must also include /zappa/zappa.js
in your page, before /foo.js
.
@shared '/index.js': ->
sum = (a, b) -> a + b
@helper role: (name) ->
unless @user.role is name
if @request? then @redirect '/login'
else if window? then alert "This is not the page you're looking for."
else if @socket? then client.disconnect()
@get '/admin': ->
@role 'admin'
# admin stuff
@on 'delete everything': ->
@role 'admin'
@client '/index.js': ->
@get '#/admin': ->
@role 'admin'
# admin stuff
Same as @client
, but also makes the elements defined in the function available at the server-side.
@coffee '/foo.js': ->
alert 'hi!'
Serves ";#{coffeescript_helpers}(#{your_function})();"
as /foo.js
, with content-type application/javascript
.
@js '/foo.js': '''
alert('hi!');
'''
Serves the string as /foo.js
, with content-type application/javascript
.
@css '/foo.css': '''
font-family: sans-serif;
'''
Serves the string as /foo.css
, with content-type text/css
.
@stylus '/foo.css': '''
border-radius()
-webkit-border-radius arguments
-moz-border-radius arguments
border-radius arguments
body
font 12px Helvetica, Arial, sans-serif
a.button
border-radius 5px
'''
Compiles the string with stylus and serves the results as /foo.css
, with content-type text/css
.
You must have stylus installed with npm install stylus
.
Note: To disable this method, use:
require('zappajs') css:[], ->
This is not enabled by default.
require('zappajs').run css:'less', ->
@less '/foo.css': '''
.border-radius(@radius) {
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
border-radius: @radius;
}
body {
font: 12px Helvetica, Arial, sans-serif;
}
a.button {
.border-radius(5px);
}
'''
Compiles the string with less and servers the results as '/foo.css', with content-type text/css
.
You must have less installed with npm install less
.
Note: Any other CSS template module that provides a .render
method might be used in a similar way.
The same object that is exported when you require 'zappa'
. See the "exports" section.
The object returned by require 'express'
.
The object returned by require('socket.io').listen
.
The object returned by express.createServer
.
Shortcut to @app.use
. It can be used in a number of additional ways:
It accepts multiple parameters:
@use express.bodyParser(), @app.router, express.cookies()
Strings:
@use 'bodyParser', @app.router, 'cookies'
And objects:
@use 'bodyParser', static: __dirname + '/public', session: {secret: 'fnord'}, 'cookies'
When passing strings and objects, zappa's own middleware will be used if available, or express (connect) middleware otherwise.
Currently available zappa middleware are:
Same as @express.static(root + '/public')
, where root
is the directory of the first file that required zappa.
Serves /zappa/zappa.js
, /zappa/jquery.js
and /zappa/sammy.js
. Automatically added by @client
and @shared
if not added before.
Shortcut to @app.configure
. Accepts an object as param. Ex.:
@configure
development: => @use 'foo'
production: => @use 'bar'
Shortcut to @app.set
. Accepts an object as param. Ex.:
@set foo: 'bar', ping: 'pong'
Shortcut to @app.enable
. Accepts multiple params in one go. Ex.:
@enable 'foo', 'bar'
Shortcut to @app.disable
. Accepts multiple params in one go. Ex.:
@disable 'foo', 'bar'
Shortcut to @app.register
. Accepts an object as param. Ex.:
@register eco: require 'eco'
Note that while @app.register '.eco'
uses a dot, @register eco
doesn't.
Directly from express.
Directly from express.
Directly from express.
Shortcut to @request.query
Shortcut to @request.body
Shortcut to @request.params
Shortcut to @request.session
Shortcut to @response.send
.
Shortcut to @response.render
.
Adds the following features:
-
You can use the syntax:
@render name: {foo: 'bar'}
. -
You can use inline views (see
@view
). -
You can use
postrender
s:render 'index', postrender: 'foo'
. -
If the setting
databag
is on, the databag will be automatically available to templates asparams
.
Shortcut to @response.redirect
.
Directly from socket.io.
Directly from socket.io.
Directly from socket.io. Provides acknowledgement of messages sent by @emit on the client.
@on foo: ->
@ack 'Got it!'
@client '/index.js', ->
@connect()
$ =>
@emit start: 'now', (data) ->
alert data # 'Got it!'
Shortcut to @socket.id
.
An empty object unique for each socket. You can put data pertaining to the client here, as an alternative to @socket.set
.
Shortcut to socket.emit
. Send a message to the client.
Adds the following features:
- You can use the syntax:
@emit name: {foo: 'bar'}
.
Shortcut to socket.broadcast
. Send a message to all clients except ours.
- You can use the syntax:
@broadcast name: {foo: 'bar'}
.
Shortcut to socket.leave
.
Shortcut to socket.leave
.
Broadcast to a room. Do not copy our client.
Broadcast to a room, including our client.
The normal view scope is a CoffeeCup scope.
This is the scope inside a @client
or @shared
callback.
Route with sammy.js.
Should be called first when the client is started to establish the Socket.IO websocket with the server.
Event handlers with socket.io.
Send a message to the server.
# Send a message but no data
@emit 'message'
# Send a message with associated data
@emit 'message', data
@emit message: data
# Send multiple messages at once
@emit message1: data1, message2: data2
# Callback receives acknowledgment from server's @ack
@emit -> alert 'Server received it'
# Callback receives acknowledgment from server with data
@emit (data) ->
Same as its server-side counterpart. Helper functions are available in routes and socket handlers.
The client-side route-handler scope contains any client-side helper, and the following.
Sammy.js render
Sammy.js redirect
Sammy.js route parameters.
The client-side socket-handler scope contains any helper function, and the following.
The Sammy.js application.
The Socket.IO socket created during @connect()
.
The Socket.IO socket ID.
The message data (received from the server).
Same as the client-side root scope's @emit
.
You can use the following options with @set
, @enable
and @disable
.
Uses uglify-js to minify the outputs of /zappa/zappa.js
, @client
, @shared
, @coffee
, @js
.
If enabled, zappa adds the following template with the name layout
:
doctype 5
html ->
head ->
title @title if @title
if @scripts
for s in @scripts
script src: s + '.js'
script(src: @script + '.js') if @script
if @stylesheets
for s in @stylesheets
link rel: 'stylesheet', href: s + '.css'
link(rel: 'stylesheet', href: @stylesheet + '.css') if @stylesheet
style @style if @style
body @body
Values: this
or param
.
When undefined (default):
@get '/:foo': ->
foo = @query.foo
foo += '!'
@render index: {foo}
When this
(use the alternative reference for the API):
@get '/:foo': (c) ->
@foo += '!'
c.render 'index'
When param
(keep @ for the API and use the alternative reference for data):
@get '/:foo': (c) ->
c.foo += '!'
@render 'index'