Chaplin.utils → Source

Chaplin’s utils provide common functions for use throughout the project.

redirectTo([...params])

Does a in-app redirect:

  1. redirectTo('messages#show', {id: 2}) — to a named route.
  2. redirectTo({url: 'messages/2'}) — to an URL.
  3. redirectTo({controller: 'messages', action: 'show', params: {id: 2}}) — etc.

In the past, !route:route[byName] event was used for this purpose.

To use replaceState and overwrite the current URL in the history you can use the third options arg that is forwarded to Backbone's router.navigate, e.g. redirectTo('messages#show', {id: 2}, {replace: true})

reverse(routeName[,...params])

Returns the URL for a named route, appropriately filling in values given as params.

For example, if you have declared the route

match '/users/:login/profile', 'users#show'
match('/users/:login/profile', 'users#show');

you can use

Chaplin.utils.reverse 'users#show', login: 'paulmillr'
# or
Chaplin.utils.reverse 'users#show', ['paulmillr']
Chaplin.utils.reverse('users#show', {login: 'paulmillr'});
// or
Chaplin.utils.reverse('users#show', ['paulmillr']);

to yield '/users/paulmillr/profile'.

beget(parent)

  • returns a new object with parent as its prototype

A standard Javascript helper function that creates an object which delegates to another object. (see Douglas Crockford's Javascript: The Good Parts for more details). Uses Object.create when available, and falls back to a polyfill if not present.

readonly(object, [*properties])

  • returns true if successful, false if unsupported by the browser’s runtime

Makes properties of object read-only so they cannot be overwritten. The success of this operation depends on the current environment’s support.

getPrototypeChain(object)

  • Object object

Gets the whole chain of prototypes for object.

getAllPropertyVersions(object, property)

  • Object object
  • String property

Get all different value versions for property from object’s prototype chain. Usage:

class A
  prop: 1
class B extends A
  prop: 2

b = new B
getAllPropertyVersions b, 'prop'  # => [1, 2]
function A() {}
A.prototype.prop = 1;

function B() {}
B.prototype = Object.create(A);

var b = new B;
getAllPropertyVersions(b, 'prop'); // => [1, 2]

upcase(str)

  • String str
  • returns upcased version of str

Ensure the first character of str is capitalized

utils.upcase 'larry bird' # 'Larry bird'
utils.upcase 'AIR'        # 'AIR'
utils.upcase('larry bird'); // 'Larry bird'
utils.upcase('AIR');        // 'AIR'

modifierKeyPressed(event)

  • jQuery normalized event object event
  • returns boolean

Looks at an event object event to determine if the shift, alt, ctrl, or meta keys were pressed. Useful in link click handling (i.e. if you need ctrl-click or shift-click to open the link in a new window).

querystring.stringify(object)

  • Object object

Returns a query string from a hash.

querystring.parse(string)

  • String string

Returns a hash with query parameters from a query string.