CanJS

  • page
canjs  

This is the detailed documentation of the API for CanJS 2.1, a framework for building web applications that provides a lightweight inheritance system, observable objects and values, and a powerful MVC core with live-bound templates, among other resources.

If you are just starting with CanJS, you may want to try our getting started guide.

CanJS is composed of modules on the left. The following are typically distributed as part of the core framework:

The following modules are typically distributed as plugins:

You can use it out of the box on top of jQuery, Zepto, YUI, and Mootools, and it's only about 20K.

< TAG [ATTR-NAME=KEY|ATTR-VALUE] >

Create an instance of a component on a particular tag in a can.mustache template.

< TAG [ATTR-NAME="{KEY}|ATTR-VALUE"] >

Create an instance of a component on a particular tag in a can.stache template.

can.Component.extend(proto)

Extends the can.Component constructor function with prototype properties and methods.

new can.Construct([args..])

Create a new instance of a constructor function.

can.Construct([name,] [staticProperties,] instanceProperties)

Creates a new extended constructor function.

can.Construct([args...])

Create a new instance of a constructor function if constructorExtends is false.

construct.init(...args)

Called when a new instance of a can.Construct is created.

construct.setup(...args)

A setup function for the instantiation of a constructor function.

can.Construct.extend([name,] [staticProperties,] instanceProperties)

Extends `can.Construct`, or constructor functions derived from `can.Construct`, to create a new constructor function.

can.Construct.newInstance([...args])

Returns an instance of `can.Construct`.

can.Construct.setup(base, fullName, staticProps, protoProps)

A static `setup` method provides inheritable setup functionality for a Constructor function.

can.Construct.proxy(callback, [...args])

Creates a static callback function that has `this` set to the constructor function.

construct.proxy(callback, [...args])

Creates a static callback function that has `this` set to an instance of the constructor function.

construct._super([...args])

Calls the base constructor function's method.

can.Control( [staticProperties,] instanceProperties )

Create a new, extended, control constructor function.

new can.Control( element, options )

Create an instance of a control.

control.destroy()

Prepares a control for garbage collection and is a place to reset any changes the control has made.

control.on([el,] selector, eventName, func)

Bind an event handler to a Control, or rebind all event handlers on a Control.

control.on()

Rebind all of a control's event handlers.

control.setup(element, options)

Perform pre-initialization logic for control instances and classes.

can.Control.extend( [staticProperties,] instanceProperties )

Create a new, extended, control constructor function.

update(newOptions)

Reconfigure a control.

jQuery.fn.control([type])

Get the Control associated with elements.

jQuery.fn.controls([type])

Get the Controls associated with elements.

new can.List([array])

Create an observable array-like object.

list.attr()

Gets an array of all the elements in this `can.List`.

list.attr(index)

Reads an element from this `can.List`.

list.attr(index, value)

Assigns _value_ to the index _index_ on this `can.List`, expanding the list if necessary.

list.attr(elements[, replaceCompletely])

Merges the members of _elements_ into this List, replacing each from the beginning in order.

list.concat(...args)

Merge many collections together into a List.

list.each( callback(item, index) )

`each` iterates through the Map, calling a function for each element.

list.filter(filterFunc, context)

Filter the elements of a List, returning a new List instance with just filtered items.

list.forEach(callback[, thisArg])

Call a function for each element of a List.

list.indexOf(item)

`indexOf` finds the position of a given item in the List.

list.join(separator)

`join` turns a List into a string by inserting _separator_ between the string representations of all the elements of the List.

list.pop()

`push` removes an element from the end of a List.

list.push(...elements)

`push` adds elements onto the end of a List.]

list.replace(collection)

Replace all the elements of a List.

list.reverse()

`reverse` reverses the elements of the List in place.

list.shift()

`shift` removes an element from the beginning of a List.

list.slice([start[, end]])

`slice` creates a copy of a portion of the List.

list.splice(index[, howMany[, ...newElements]])

Insert and remove elements from a List.

list.unshift(...elements)

`unshift` adds elements onto the beginning of a List.

can.List.extend([name,] [staticProperties,] instanceProperties)

Creates a new extended constructor function.

list.always( alwaysCallback )

Add handlers to be called when the list is either resolved or rejected.

list.done( doneCallback )

Add handlers to be called when the list is resolved.

list.fail( failCallback )

Add handlers to be called when the list is rejected.

list.isPending()

Returns if the state of the list is pending.

list.isRejected()

Returns if the state of the list is rejected.

list.isResolved()

Returns if the state of the list is resolved.

list.then( doneFilter, [failFilter] )

Add handlers to be called when the list is resolved or rejected.

new can.Map([props])

Creates a new instance of can.Map.

can.Map([name,] [staticProperties,] instanceProperties)

Creates a new extended constructor function.

map.attr()

Gets a collection of all the properties in this `can.Map`.

map.attr(key)

Reads a property from this `can.Map`.

map.attr(key, value)

Assigns _value_ to a property on this `can.Map` called _key_.

map.attr(obj[, removeOthers])

Assigns each value in _obj_ to a property on this `can.Map` named after the corresponding key in _obj_, effectively merging _obj_ into the Map.

map.bind(eventType, handler)

Bind event handlers to an Map.

map.compute(attrName)

Make a can.compute from an observable property.

map.each( callback(item, propName ) )

`each` iterates through the Map, calling a function for each property value and key.

map.removeAttr(attrName)

Remove a property from an Map.

map.serialize()

Get the serialized Object form of the map.

map.unbind(eventType[, handler])

Unbind event handlers from an Map.

can.Map.keys(map)

Iterate over the keys of an Map.

new can.LazyLazyMap([props])

Creates a new instance of can.LazyMap.

observe.serialize([attrName])

Serializes the observe's properties using the attribute plugin.

map.backup()

`backup` backs up the current state of the properties of an Observe and marks the Observe as clean.

map.isDirty([deep])

`isDirty` checks whether any properties have changed value or whether any properties have been added or removed since the last time the Observe was backed up.

map.restore( [deep] )

`restore` sets the properties of an Observe back to what they were the last time backup was called.

observe.delegate( selector, event, handler )

`delegate( selector, event, handler(ev,newVal,oldVal,from) )` listen for changes in a child attribute from the parent.

observe.undelegate( selector, event, handler )

`undelegate( selector, event, handler )` removes a delegated event handler from an observe.

constructorFunc

A constructor function can be provided that is called to convert incoming values set on this property, like: define: { prop: { Type: Person } }

constructorFunc

A constructor function can be provided that is called to create a default value used for this property, like: define: { prop: { Value: Array }, person: { Value: Person } }

get( )

A get function defines the behavior of what happens when a value is read on a can.Map.

remover( currentValue )

Called when an attribute is removed.

serializer( currentValue )

Called when an attribute is removed.

set( [newVal,] [setValue] )

A set function defines the behavior of what happens when a value is set on a can.Map.

defaulter()

A function can be provided that returns the default value used for this property, like: define: { prop: { value: function(){ return []; } } } If the default value should be an object of some type, it should be specified as the return value of a function (the above call signature) so that all instances of this map don't point to the same object.

defaulVal

Any value can be provided as the default value used for this property, like: define: { prop: { value: 'foo' } }

setATTR: function(newValue,setValue,setErrors)

Specifies a setter method for the `ATTR` attribute.

can.classize(str)

`can.classize` splits a string by underscores or dashes and capitalizes each part before joining them back together.

observe.validateInclusionOf(attrNames, inArray, options)

Validates whether the values of the specified attributes are available in a particular array.

observe.validateLengthOf(attrNames, min, max, options)

Validates that the specified attributes' lengths are in the given range.

observe.validatePresenceOf(attrNames, options)

Validates that the specified attributes are not blank.

observe.validateRangeOf(attrNames, low, hi, options)

Validates that the specified attributes are in the given numeric range.

observe.validatesNumericalityOf(attrNames)

Validates that the specified attributes is a valid Number.

new can.Model([options])

Creates a new instance of _ModelConstructor_.

new can.Model.List()

Create an empty model list.

new can.Model.List( [models] )

Create a model list with the provided model instances.

new can.Model.List( deferred )

Create a model list with the results of `deferred`.

new can.Model.List( params )

Create an initially empty model list, but use the model's findAll to get a list of models and add it to this empty list.

can.compute( getterSetter[, context] )

Create a compute that derives its value from can.Maps and other can.computes.

can.compute( initialValue [, settings] )

Creates a compute from a value and optionally specifies how to read, update, and listen to changes in dependent values.

can.compute( initialValue, setter(newVal,oldVal) )

Create a compute that has a setter that can adjust incoming new values.

can.compute( object, propertyName [, eventName] )

Create a compute from an object's property value.

compute.bind(eventType, handler)

Bind an event handler to a compute.

compute.unbind(eventType[, handler])

Unbind an event handler from a compute.

can.ejs( [id,] template )

Creates an instance of an EJS template.

<% CODE %>

Runs JavaScript Code.

<%= CODE %>

Runs JS Code and writes the _escaped_ result into the result of the template.

<%== CODE %>

Runs JS Code and writes the _unescaped_ result into the result of the template.

<%% CODE %>

Renders <% CODE %> as text in result of the template rather than running CODE itself.

<%# CODE %>

Used for explicitly for comments.

can.extend(YourClass.prototype, can.event)

Adds event functionality to `YourClass` objects.

can.extend(YourClass.prototype, can.event, { propagate: "parent" })

Adds event functionality with event propagation to `YourClass` objects.

obj.addEvent( event, handler )

Add a basic event listener to an object.

can.event.addEvent.call( obj, event, handler )

This syntax can be used for objects that don't include the `can.event` mixin.

obj.bind( event, handler )

Add a basic event listener to an object.

can.event.bind.call( obj, event, handler )

This syntax can be used for objects that don't include the `can.event` mixin.

obj.dispatch( event, args )

Dispatches/triggers a basic event on an object.

can.event.dispatch.call( obj, event, args )

This syntax can be used for objects that don't include the `can.event` mixin.

obj.listenTo( other, event, handler )

Listens for an event on another object.

can.event.listenTo.call( obj, other, event, handler )

This syntax can be used for objects that don't include the `can.event` mixin.

obj.off( event, handler )

Removes a basic event listener from an object.

can.event.off.call( obj, event, handler )

This syntax can be used for objects that don't include the `can.event` mixin.

obj.on( event, handler )

Add a basic event listener to an object.

can.event.on.call( obj, event, handler )

This syntax can be used for objects that don't include the `can.event` mixin.

obj.one( event, handler )

Adds a basic event listener that listens to an event once and only once.

obj.removeEvent( event, handler )

Removes a basic event listener from an object.

can.event.removeEvent.call( obj, event, handler )

This syntax can be used for objects that don't include the `can.event` mixin.

obj.stopListening( other, event, handler )

Stops listening for an event on another object.

can.event.stopListening.call( obj, other, event, handler )

This syntax can be used for objects that don't include the `can.event` mixin.

obj.trigger( event, args )

Dispatches/triggers a basic event on an object.

can.event.trigger.call( obj, event, args )

This syntax can be used for objects that don't include the `can.event` mixin.

obj.unbind( event, handler )

Removes a basic event listener from an object.

can.event.unbind.call( obj, event, handler )

This syntax can be used for objects that don't include the `can.event` mixin.

obj.undelegate( selector, event, handler )

Provides a compatibility layer for removing delegate event listeners.

can.event.undelegate.call( obj, selector, event, handler )

This syntax can be used for objects that don't include the `can.event` mixin.

can.fixture( url, toUrl )

Trap requests from one url and redirect them from another.

can.fixture( url, handler(request, response, requestHeaders) )

Trap requests to a url and provide the response with a callback function.

can.fixture(fixtures)

Configures multiple ajax traps.

store.create(request, callback)

Simulate creating a Model with a fixture.

store.destroy(request, callback)

Simulate destroying a Model on a fixture.

store.find(settings)

Get an item from the store by ID.

store.findAll(request)

`store.findAll(request)` simulates a request to get a list items from the server.

store.findOne(request, callback)

Simulate a findOne request on a fixture.

store.reset()

Reset the fixture store.

store.update(request, callback)

Simulate an update on a fixture.

can.fixture.rand([min,] max)

Create a random number or selection.

can.fixture.rand(choices, min[ ,max])

Create a random number or selection.

can.fixture.store(count, make[, filter])

Make a store of objects to use when making requests against fixtures.

can.mustache( [id,] template )

Creates an instance of a mustache template.

{{key}}

Insert the value of the key into the output of the template.

{{{key}}}

Behaves just like {{key}} and {{helper}} but does not escape the result.

{{&key}}

The `{{&key}}` tag is an alias for {{{key}}}, behaving just like {{key}} and {{helper}} but does not escape the result.

{{#key}}BLOCK{{/key}}

Render blocks of text one or more times, depending on the value of the key in the current context.

{{/key}}

Ends a {{#key}} or {{#helper}} block.

{{^key}}BLOCK{{/key}}

Render blocks of text if the value of the key is falsey.

{{>key}}

Render another template within the current template.

{{!key}}

The comment tag operates similarly to a `` tag in HTML.

{{helper [args...] [hashProperty=hashValue...]}}

Calls a mustache helper function or a function.

{{#helper [args...] [hashName=hashValue...]}}BLOCK{{/helper}}

Calls a mustache helper function or a function with a block to render.

{{#helper [args...] [hashName=hashValue...]}}BLOCK{{else}}INVERSE{{/helper}}

Calls a mustache helper function or a function with a `fn` and `inverse` block to render.

{{#if key}}BLOCK{{/if}}

Renders the `BLOCK` template within the current template.

{{#helper}}BLOCK{{else}}INVERSE{{/helper}}

Creates an `inverse` block for a helper function's options argument's `inverse` property.

{{#unless key}}BLOCK{{/unless}}

Render the block of text if the key's value is falsey.

{{#each key}}BLOCK{{/each}}

Render the block of text for each item in key's value.

{{#with key}}BLOCK{{/with}}

Changes the context within a block.

{{data name}}

Adds the current context to the element's can.data.

{{(el) -> CODE}}

Executes an element callback with the inline code on the element.

{{#log [message]}}

Logs the context of the current block with an optional message.

{{@index [offset]}}

Insert the index of an Array or can.List we are iterating on with [#each](can.mustache.helpers.each)

{{@key}}

Insert the property name of an Object or attribute name of a can.Map that we iterate over with [#each](can.mustache.helpers.each)

can.route( template [, defaults] )

Create a route matching rule.

can.route.current( data )

Check if data represents the current route.

can.route.deparam( url )

Extract data from a route path.

can.route.link( innerText, data, props [, merge] )

Make an anchor tag (``) that when clicked on will update can.route's properties to match those in `data`.

can.route.map(MapConstructor)

Assign a can.Map instance that acts as can.route's internal can.Map.

can.route.map(mapInstance)

Assign a can.Map instance that acts as can.route's internal can.Map.

can.route.param( data )

Get a route path from given data.

can.route.ready()

Sets up the two-way binding between the hash and the can.route observable map and sets the can.route map to its initial values.

can.route.url( data [, merge] )

Make a URL fragment that when set to window.location.hash will update can.route's properties to match those in `data`.

can.stache(template)

Processes the template and returns a renderer function that renders the template with data and local helpers.

{{key}}

Insert the value of the key into the output of the template.

{{{key}}}

Behaves just like {{key}} and {{helper}} but does not escape the result.

{{&key}}

The `{{&key}}` tag is an alias for {{{key}}}, behaving just like {{key}} and {{helper}} but does not escape the result.

{{#key}}BLOCK{{/key}}

Render blocks of text one or more times, depending on the value of the key in the current context.

{{/key}}

Ends a {{#key}} or [can.stache.tags.sectionHelper {{#helper}}] block.

{{^key}}BLOCK{{/key}}

Render blocks of text if the value of the key is falsey.

{{>key}}

Render another template within the current template.

{{!key}}

The comment tag operates similarly to a `` tag in HTML.

{{helper [args...] [hashProperty=hashValue...]}}

Calls a stache helper function or a function.

{{#helper [args...] [hashName=hashValue...]}}BLOCK{{/helper}}

Calls a stache helper function or a function with a block to render.

{{#helper [args...] [hashName=hashValue...]}}BLOCK{{else}}INVERSE{{/helper}}

Calls a stache helper function or a function with a `fn` and `inverse` block to render.

{{#if key}}BLOCK{{/if}}

Renders the `BLOCK` template within the current template.

{{#helper}}BLOCK{{else}}INVERSE{{/helper}}

Creates an `inverse` block for a helper function's options argument's `inverse` property.

{{#unless key}}BLOCK{{/unless}}

Render the block of text if the key's value is falsey.

{{#each key}}BLOCK{{/each}}

Render the block of text for each item in key's value.

{{#with key}}BLOCK{{/with}}

Changes the context within a block.

{{data name}}

Adds the current context to the element's can.data.

{{#log [message]}}

Logs the context of the current block with an optional message.

{{@index [offset]}}

Insert the index of an Array or can.List we are iterating on with [#each](can.stache.helpers.each)

{{@key}}

Insert the property name of an Object or attribute name of a can.Map that we iterate over with [#each](can.stache.helpers.each)

can.$(element)

Make a library's nodelist.

can.Deferred()

`can.Deferred` is a object that allows users to assign and chain callback function(s) for the success or failure state of both asynchronous and synchronous function(s).

can.Object.subset(subset, set, compares)

Compares if subset is a subset of set.

can.Object.subsets(checkSet, sets, compares)

Returns the sets in 'sets' that are a subset of checkSet ```js can.Object.subsets({userId: 20}, [ {userId: 20, limit: 30}, {userId: 5}, {} ]) //-> [{userId: 20, limit: 30}] ```

can.addClass(nodeList, className)

Add a class to elements.

can.ajax(settings)

Make an AJAX request.

can.append(nodeList, html)

Append content to elements.

can.batch.trigger(item, event [, args])

Trigger an event to be added to the current batch.

can.bind.call(target, eventName, handler)

Listen for events on an object.

can.buildFragment(html, node)

Make a document fragment.

can.camelize(str)

Capitalize the first letter after each hyphen in a string.

can.capitalize(str)

Capitalize the first letter of a string.

can.data(nodeList, key, value)

Associate data with or retrieve data from DOM nodes.

can.data(nodeList, key)

Associate data with or retrieve data from DOM nodes.

can.delegate.call(element, selector, eventName, handler)

Listen for events from the children of an element.

can.deparam(params)

Takes a string of name value pairs and returns a Object literal that represents those params.

can.each(collection, callback)

Iterate through an array or object.

can.esc(str)

Escapes a string for insertion into HTML.

can.extend(target, ...obj)

Merge objects together.

can.getObject(name, roots, add)

Gets an object from a string.

can.hyphenate(str)

Adds a hyphen before each uppercase letter and converts the entire string to lower case.

can.isArray(obj)

Check if an object is an array.

can.isDeferred(subject)

Check if an object is a Deferred.

can.isEmptyObject(obj)

Check if an object has no properties.

can.isFunction(obj)

Check if an Object is a function.

can.makeArray(arrLike)

Convert an array-like object to an Array.

can.off.call(target, eventName, handler)

Stop listening for events on an object.

can.on.call(target, eventName, handler)

Listen for events on an object.

can.param(obj)

Serialize an object into a query string.

can.proxy(fn, context)

Bind a function to its context.

can.remode(nodeList)

Remove elements from the DOM.

can.sub(str, data, remove, s)

Returns a string with {param} replaced values from data.

can.trigger(target, eventName[, args])

Trigger an event on an object.

can.trim(str)

Trim whitespace off a string.

can.unbind.call(target, eventName, handler)

Stop listening for events on an object.

can.undelegate.call(element, selector, eventName, handler)

Stop listening for events from the children of an element.

can.underscore(str)

Takes a CamelCase or mixedCase string and underscores the string on the capital letter.

can.when(deferred)

Call a callback when a Deferred resolves.

can.view( idOrUrl, data[, helpers] )

Loads a template, renders it with data and helper functions and returns the HTML of the template within a documentFragment.

can.view( idOrUrl )

Registers or loads a template and returns a renderer function that can be used to render the template with `data` and `helpers`.

new can.view.Options(options, [parent])

Create a helper lookup node for keys.

can.view.attr( attributeName, attrHandler(el, attrData) )

Register custom behavior for an attribute.

can.view.ejs( [id,] template )

Register an EJS template string and create a renderer function.

can.view.hook(callback)

Create a hookup to insert into templates.

can.mustache( [id,] template )

Register a Mustache template string and create a renderer function.

can.view.register(info)

Register a templating language.

can.view.tag( tagName, tagHandler(el, tagData) )

Registers the `tagHandler` callback when `tagName` is found in a template.

can-EVENT='KEY'

Specify a callback function to be called on a particular event.

can-value='KEY'

Binds the element's value or checked property to the value specified by key.

<input type='radio' can-value='KEY' value='VALUE'/>

If the radio element is checked, sets the observable specified by `can-value` to match the value of `value` attribute.

<select can-value='KEY'/>

Cross binds the selected option value with an observable value.

<select multiple can-value='KEY'/>

Cross binds the selected option values with an observable value.