can
Version:
MIT-licensed, client-side, JavaScript framework that makes building rich web applications easy.
1,388 lines (965 loc) • 57.5 kB
HTML
<!DOCTYPE html>
<!--####################################################################
THIS IS A GENERATED FILE -- ANY CHANGES MADE WILL BE OVERWRITTEN
INSTEAD CHANGE:
source: [object Object]
@module can-connect
######################################################################## -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>CanJS - can-connect</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" type="text/css" href="./static/bundles/bit-docs-site/static.css">
<link rel="shortcut icon" sizes="16x16 24x24 32x32 48x48 64x64" href="/docs/images/canjs_favicon.ico">
<link rel="apple-touch-icon" sizes="57x57" href="../docs/images/canjs_favicon_57x57.png">
<link rel="apple-touch-icon-precomposed" sizes="57x57" href="../docs/images/canjs_favicon_57x57.png">
<link rel="apple-touch-icon" sizes="72x72" href="../docs/images/canjs_favicon_72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../docs/images/canjs_favicon_114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="../docs/images/canjs_favicon_128x128.png">
<link rel="apple-touch-icon" sizes="144x144" href="../docs/images/canjs_favicon_144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="../docs/images/canjs_favicon_152x152.png">
<meta content="yes" name="apple-mobile-web-app-capable">
<meta name="apple-mobile-web-app-status-bar-style" content="white-translucent">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-2302003-11', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger"/>
<label for="nav-trigger">Menu</label>
<div id="everything">
<div id="left" class="column">
<div class="top-left">
<div class="brand">
<div class="logo">
<a href="../index.html" alt="CanJS"></a>
<div class="dropdown project-dropdown">
<a href="https://donejs.com/">DoneJS</a>
<a href="http://stealjs.com/">StealJS</a>
<a href="http://jquerypp.com/">jQuery ++</a>
<a href="https://funcunit.com/">FuncUnit</a>
<a href="http://documentjs.com/">DocumentJS</a>
</div>
</div>
<div class="version">
<div class="version-number">
3.0.0
</div>
<div class="dropdown version-dropdown">
<a href="https://v2.canjs.com">2.3.27</a>
</div>
</div>
</div>
<div class="search-bar">
<p>
</p>
</div>
</div>
<div class="bottom-left">
<div class="social-side-container">
<ul class="social-side">
<li>
<a class="header-mobile github" href="https://github.com/canjs/canjs" target="_blank"><img class="social-icon-small" src="../docs/images/github.png">Github</a>
</li>
<li>
<a class="header-mobile twitter" href="https://twitter.com/canjs" target="_blank"><img class="social-icon-small" src="../docs/images/twitter.png">Twitter</a>
</li>
</ul>
<ul class="social-side">
<li>
<a class="header-mobile" href="https://gitter.im/canjs/canjs" target="_blank">Chat</a>
</li>
<li>
<a class="header-mobile" href="http://forums.donejs.com/c/canjs" target="_blank">Forum</a>
</li>
</ul>
</div>
<ul>
<li class="
">
<a class="page"
href="guides.html"
title="Welcome to CanJS! These guides are here to help you develop and improve your relationship with CanJS. After all, picking a JavaScript framework is a commitment. We want CanJS to be the
framework you marry. This page helps you know how advance through the different stages of this
relationship:">
Guides
</a>
</li>
<li class="
parent
expanded">
<a class="page"
href="can-core.html"
title="The best, most hardened and generally useful libraries in CanJS.">
Core
</a>
<ul>
<li class="
">
<a class="module"
href="can-component.html"
title="Create a custom element that can be used to manage widgets or application logic.">
can-component
</a>
</li>
<li class="
">
<a class="module"
href="can-compute.html"
title="Create an observable value.">
can-compute
</a>
</li>
<li class="current
parent
expanded">
<a class="module"
href="can-connect.html"
title="can-connect provides persisted data middleware. Use it to assemble powerful model layers for any JavaScript project.">
can-connect
</a>
<ul>
<li>
<span>behaviors</span>
<ul>
<li class="
">
<a class="module"
href="can-connect/base/base.html"
title="The base behavior added to every connect behavior.">
./base/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/cache-requests/cache-requests.html"
title="Caches reponse data and uses it to prevent future requests or make future requests smaller.">
./cache-requests/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/can/map/map.html"
title="Make a connection use a map type.">
./can/map/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/can/ref/ref.html"
title="Handle references to instances in the raw data returned by the server.">
./can/ref/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/constructor/callbacks-once/callbacks-once.html"
title="Prevents unecessary calls to the instance callback methods.">
./constructor/callbacks-once/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/constructor/constructor.html"
title="Adds the ability to operate on special types instead of plain JavaScript Objects
and Arrays.">
./constructor/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/constructor/store/store.html"
title="Supports saving and retrieving lists and instances in a store.">
./constructor/store/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/data/callbacks/callbacks.html"
title="Calls callback methods as a result of raw DataInterface requests.">
./data/callbacks/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/data/callbacks-cache/callbacks-cache.html"
title="Callback base.cacheConnection methods when data interface callbacks
are called.">
./data/callbacks-cache/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/data/combine-requests/combine-requests.html"
title="Combines multiple incoming requests into one if possible.">
./data/combine-requests/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/data/localstorage-cache/localstorage-cache.html"
title="Saves raw data in localStorage.">
./data/localstorage-cache/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/data/memory-cache/memory-cache.html"
title="Saves raw data in JavaScript memory that disappears when the page refreshes.">
./data/memory-cache/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/data/parse/parse.html"
title="Extract response data into a format needed for other extensions.">
./data/parse/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/data/url/url.html"
title="">
./data/url/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/data/worker/worker.html"
title="Connects a connection to another connection in a worker thread.">
./data/worker/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/fall-through-cache/fall-through-cache.html"
title="A fall through cache that checks another cacheConnection.">
./fall-through-cache/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/real-time/real-time.html"
title="Update lists to include or exclude instances based
on set logic.">
./real-time/
</a>
</li>
</ul>
</li>
<li>
<span>modules</span>
<ul>
<li class="
">
<a class="module"
href="can-connect/can/base-map/base-map.html"
title="Create connection with many of the best behaviors in can-connect and hook it up to
a map.">
./can/base-map/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/can/model/model.html"
title="Exports a constructor that works very similar to can.Model.">
./can/model/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/can/super-map/super-map.html"
title="Create connection with many of the best behaviors in can-connect and hook it up to
a map.">
./can/super-map/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/can/tag/tag.html"
title="Makes either getList or getInstance">
./can/tag/
</a>
</li>
<li class="
">
<a class="module"
href="can-connect/helpers/weak-reference-map.html"
title="Provides a map that only contains keys that are referenced.">
./helpers/weak-reference-map
</a>
</li>
</ul>
</li>
<li>
<span>data types</span>
<ul>
<li class="
">
<a class="typedef"
href="can-connect/DataInterface.html"
title="The most common raw data methods.">
DataInterface
</a>
</li>
<li class="
">
<a class="typedef"
href="can-connect/Instance.html"
title="An instance of some JavaScript type.">
Instance
</a>
</li>
<li class="
">
<a class="typedef"
href="can-connect/InstanceInterface.html"
title="">
InstanceInterface
</a>
</li>
<li class="
">
<a class="typedef"
href="can-connect.List.html"
title="A list type.">
List
</a>
</li>
<li class="
">
<a class="typedef"
href="can-connect.listData.html"
title="The data format used to create typed lists.">
ListData
</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="
">
<a class="module"
href="can-define.html"
title="Exports the define method that defines observable properties and their behavior on a prototype object.">
can-define
</a>
</li>
<li class="
">
<a class="module"
href="can-define/list/list.html"
title="Create observable lists.">
can-define/list/list
</a>
</li>
<li class="
">
<a class="module"
href="can-define/map/map.html"
title="Create observable objects.">
can-define/map/map
</a>
</li>
<li class="
">
<a class="function"
href="can-route.html"
title="Manage browser history and client state by synchronizing the window.location.hash with a map.">
can-route
</a>
</li>
<li class="
">
<a class="module"
href="can-route-pushstate.html"
title="Changes can-route to use pushstate
to change the window's pathname instead
of the hash.
var route = require("can-route-pushstate");
route("{page}", { page: "home" });
route.ready();
route.attr("page", "user");
location.pathname; // -> "/user"">
can-route-pushstate
</a>
</li>
<li class="
">
<a class="module"
href="can-set.html"
title="can-set is a utility for comparing sets that are represented by the parameters commonly passed to service requests.">
can-set
</a>
</li>
<li class="
">
<a class="module"
href="can-stache.html"
title="Live binding Mustache and Handlebars-compatible templates.">
can-stache
</a>
</li>
<li class="
">
<a class="module"
href="can-stache/helpers/route.html"
title="Adds stache helpers that use can-route.">
can-stache/helpers/route
</a>
</li>
<li class="
">
<a class="module"
href="can-stache-bindings.html"
title="Provides template event, one-way, and two-way bindings.">
can-stache-bindings
</a>
</li>
</ul>
</li>
<li class="
">
<a class="page"
href="can-ecosystem.html"
title="Useful libraries that extend or add important features to the core collection.">
Ecosystem
</a>
</li>
<li class="
">
<a class="page"
href="can-infrastructure.html"
title="Utility libraries that power the core and ecosystem collection.">
Infrastructure
</a>
</li>
<li class="
">
<a class="page"
href="can-legacy.html"
title="Former libraries that we still accept patches for, but are not under active development.">
Legacy
</a>
</li>
</ul>
</div>
</div>
<div id="right" class="column">
<div class="top-right">
<div class="top-right-top">
<ul class="top-right-bitovi">
<li class="dropdown">
<a href="http://bitovi.com" class="bitovi icon-bits">Bitovi</a>
<ul class="dropdown-menu">
<li><a href="http://bitovi.com">Bitovi.com</a></li>
<li><a href="http://bitovi.com/blog/">Blog</a></li>
<li><a href="http://bitovi.com/consulting/">Consulting</a></li>
<li><a href="http://bitovi.com/training/">Training</a></li>
<li><a href="http://bitovi.com/open-source/">Open Source</a></li>
</ul>
</li>
</ul>
<div class="brand">
<div class="logo">
<a href="../index.html" alt="CanJS"></a>
</div>
</div>
<ul class="top-right-links">
<li>
<a href="https://gitter.im/canjs/canjs">Chat</a>
</li>
<li>
<a href="http://forums.donejs.com/c/canjs">Forum</a>
</li>
<li>
<a class="github-button nav-social" href="https://github.com/canjs/canjs" data-count-href="/canjs/canjs/stargazers" data-count-api="/repos/canjs/canjs#stargazers_count">Star</a>
</li>
<li>
<a href="https://twitter.com/canjs" class="twitter-follow-button nav-social" data-show-count="true" data-show-screen-name="false">Follow @canjs</a><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</li>
</ul>
</div>
<div class="breadcrumb">
<li><a href="../index.html">CanJS</a></li> /
<li><a href="can-core.html">Core</a></li> /
<li><a href="can-connect.html">can-connect</a></li>
<li class="breadcrumb-dropdown">/ <a> On this page</a>
<ul class="on-this-page"></ul>
</li>
<div class="nav-toggle" title="Back to top"></div>
</div>
</div>
<div class="bottom-right">
<article>
<section class="title">
<div class="page-type">
<h1>can-connect</h1>
<div>module</div>
</div>
<section class="description">
<p><code>can-connect</code> provides persisted data middleware. Use it to assemble powerful model layers for any JavaScript project.</p>
</section>
</section>
<section class="on-this-page-table">
</section>
<section class="title-footer">
<ul class="title-social">
<li>
<a class="npm-button" href="https://www.npmjs.com/package/can-connect">
<img src="https://img.shields.io/badge/npm%20package-1.0.11-brightgreen.svg" alt="npm package badge" />
</a>
</li>
<li>
<a class="github-button nav-social" href="https://github.com/canjs/can-connect"
data-count-href="/canjs/can-connect/stargazers"
data-count-api="/repos/canjs/can-connect#stargazers_count">Star</a>
</li>
</ul>
<ul class="title-links">
<!-- <li><a href="#">docco</a></li> -->
<li><a href="//github.com/canjs/can-connect/tree/v1.0.11/can-connect.md">source</a></li>
<!-- <li><a href="#">download</a></li> -->
<!-- <li><a href="#">tests</a></li> -->
</ul>
</section>
<div class="signature">
<h2 class="signature-title">
<code>connect(behaviors, options)</code>
</h2>
<p>Goes through every behavior and assembles them into a final
connection.</p>
<pre><code class="language-js">var connect = require("can-connect");
var todosConnection = connect([
require("can-connect/data/url/url"),
require("can-connect/data/constructor/constructor")
],{
url: "/api/todos"
});
</code></pre>
<div class="parameters">
<h3 class="parameters-title">Parameters</h3>
<ol>
<li><b>behaviors</b> <code>{Array<can-connect/Behavior>}</code>: <p>An array of
behaviors that will be used to compose the final connection.</p>
</li>
<li><b>options</b> <code>{Object}</code>: <p>an object of configuration
options.</p>
</li>
</ol>
</div>
</div>
<section class="body">
<p><code>can-connect</code> comes with the following behaviors that:</p>
<p>Load data:</p>
<ul>
<li><a href="can-connect/data/url/url.html" title="">can-connect/data/url/url</a> - Persist data to restful or other types of services.</li>
<li><a href="can-connect/data/parse/parse.html" title="Extract response data into a format needed for other extensions.">can-connect/data/parse/parse</a> - Extract response data into a format needed for other extensions.</li>
</ul>
<p>Convert data into special types:</p>
<ul>
<li><a href="can-connect/constructor/constructor.html" title="Adds the ability to operate on special types instead of plain JavaScript Objects
and Arrays.">can-connect/constructor/constructor</a> - Create instances of a constructor function or list type.</li>
<li><a href="can-connect/constructor/store/store.html" title="Supports saving and retrieving lists and instances in a store.">can-connect/constructor/store/store</a> - Create only a single instance for a given id or a single list for a set.</li>
</ul>
<p>Real time:</p>
<ul>
<li><a href="can-connect/real-time/real-time.html" title="Update lists to include or exclude instances based
on set logic.">can-connect/real-time/real-time</a> - Update lists and instances with server side events.</li>
</ul>
<p>Caching strategies:</p>
<ul>
<li><a href="can-connect/fall-through-cache/fall-through-cache.html" title="A fall through cache that checks another cacheConnection.">can-connect/fall-through-cache/fall-through-cache</a> - Respond with data from the <a href="connection.cacheConnection.html" title="connection.cacheConnection">cacheConnection</a> and
then update the response with data from the <code>raw CRUD Methods</code>.</li>
<li><a href="can-connect/cache-requests/cache-requests.html" title="Caches reponse data and uses it to prevent future requests or make future requests smaller.">can-connect/cache-requests/cache-requests</a> - Save response data and use it for future requests.</li>
<li><a href="can-connect/data/combine-requests/combine-requests.html" title="Combines multiple incoming requests into one if possible.">can-connect/data/combine-requests/combine-requests</a> - Combine overlapping or reduntant requests.</li>
</ul>
<p>Caching layers:</p>
<ul>
<li><a href="can-connect/data/localstorage-cache/localstorage-cache.html" title="Saves raw data in localStorage.">can-connect/data/localstorage-cache/localstorage-cache</a> - LocalStorage caching connection.</li>
<li><a href="can-connect/data/memory-cache/memory-cache.html" title="Saves raw data in JavaScript memory that disappears when the page refreshes.">can-connect/data/memory-cache/memory-cache</a> - LocalStorage caching connection.</li>
</ul>
<p>The following modules glue certain methods together:</p>
<ul>
<li><a href="can-connect/data/callbacks/callbacks.html" title="Calls callback methods as a result of raw DataInterface requests.">can-connect/data/callbacks/callbacks</a> - Glues the result of the <code>raw CRUD Methods</code> to callbacks.</li>
<li><a href="can-connect/data/callbacks-cache/callbacks-cache.html" title="Callback base.cacheConnection methods when data interface callbacks
are called.">can-connect/data/callbacks-cache/callbacks-cache</a> - Calls <a href="connection.cacheConnection.html" title="connection.cacheConnection">cacheConnection</a> methods whenever <code>raw CRUD methods</code> are called.</li>
</ul>
<p>The following modules are useful to CanJS specifically:</p>
<ul>
<li><a href="can-connect/can/map/map.html" title="Make a connection use a map type.">can-connect/can/map/map</a> - Create instances of a special <a href="can-define/map/map.html" title="Create observable objects.">can-define/map/map</a> or <a href="can-define/list/list.html" title="Create observable lists.">can-define/list/list</a> type.</li>
<li><a href="can-connect/can/super-map/super-map.html" title="Create connection with many of the best behaviors in can-connect and hook it up to
a map.">can-connect/can/super-map/super-map</a> - Create a connection for a <a href="can-define/map/map.html" title="Create observable objects.">can-define/map/map</a> or <a href="can-define/list/list.html" title="Create observable lists.">can-define/list/list</a> that uses almost all the plugins.</li>
<li><a href="can-connect/can/model/model.html" title="Exports a constructor that works very similar to can.Model.">can-connect/can/model/model</a> - Inherit from a highly compatible <a href="http://canjs.com/docs/can.Model.html">can.Model</a> implementation.</li>
<li><a href="can-connect/can/tag/tag.html" title="Makes either getList or getInstance">can-connect/can/tag/tag</a> - Create a custom element that can load data into a template.</li>
</ul>
<h2>Overview</h2>
<p>The "can-connect" module exports a <code>connect</code> function that is used to assemble different
behaviors and some options into a <code>connection</code>. For example, the following uses <code>connect</code> and
the <a href="can-connect/constructor/constructor.html" title="Adds the ability to operate on special types instead of plain JavaScript Objects
and Arrays.">can-connect/constructor/constructor</a> and <a href="can-connect/data/url/url.html" title="">can-connect/data/url/url</a> behaviors to create a <code>todoConnection</code>
connection:</p>
<pre><code class="language-js">var connect = require("can-connect");
var constructor = require("can-connect/constructor/constructor");
var dataUrl = require("can-connect/data/url/url");
var todoConnection = connect(
[constructor,dataUrl],
{
url: "/services/todos"
});
</code></pre>
<p>A connection typically provides the ability to
create, read, update, or delete (CRUD) some data source. That data source is
usually accessed through the "Instance Interface" methods:</p>
<ul>
<li><a href="can-connect/connection.get.html" title="">connection.get</a></li>
<li><a href="can-connect/connection.getList.html" title="">connection.getList</a></li>
<li><a href="can-connect/connection.save.html" title="">connection.save</a></li>
<li><a href="can-connect/connection.destroy.html" title="">connection.destroy</a></li>
</ul>
<p>For example, to get all todos from "GET /services/todos", we could write the following:</p>
<pre><code>todoConnection.getList({}).then(function(todos){ ... });
</code></pre>
<p><strong>Behaviors</strong>, like <a href="can-connect/constructor/constructor.html" title="Adds the ability to operate on special types instead of plain JavaScript Objects
and Arrays.">can-connect/constructor/constructor</a> and <a href="can-connect/data/url/url.html" title="">can-connect/data/url/url</a> implement,
extend, or require some set of <a href="#section_Interfaces">interfaces</a>. For example, <a href="can-connect/data/url/url.html" title="">can-connect/data/url/url</a> implements
the "Data Interface" methods, and <a href="can-connect/constructor/constructor.html" title="Adds the ability to operate on special types instead of plain JavaScript Objects
and Arrays.">can-connect/constructor/constructor</a> implements the
"Instance Interface" methods.</p>
<p>The <code>connect</code> method calls these behaviors in the right order to create a connection. For instance,
the <a href="can-connect/cache-requests/cache-requests.html" title="Caches reponse data and uses it to prevent future requests or make future requests smaller.">can-connect/cache-requests/cache-requests</a> behavior must be applied after the <a href="can-connect/data/url/url.html" title="">can-connect/data/url/url</a>
connection. This is because <a href="can-connect/cache-requests/cache-requests.html" title="Caches reponse data and uses it to prevent future requests or make future requests smaller.">can-connect/cache-requests/cache-requests</a>, overwrites <a href="can-connect/data/url/url.html" title="">can-connect/data/url/url</a>'s
<a href="can-connect/connection.getListData.html" title="Retrieves list of records for the given set.">getListData</a> first check a cache for the data. Only if the data is not present,
does it call <a href="can-connect/data/url/url.html" title="">can-connect/data/url/url</a>'s <a href="can-connect/connection.getListData.html" title="Retrieves list of records for the given set.">getListData</a>. So even if we write:</p>
<pre><code class="language-js">var dataUrl = require("can-connect/data/url/url");
var cacheRequests = require("can-connect/cache-requests/cache-requests/cache-requests");
connect([cacheRequests,dataUrl])
</code></pre>
<p>or</p>
<pre><code>connect([dataUrl,cacheRequests])
</code></pre>
<p>... our connection will be built in the right order!</p>
<p>A <strong>connection</strong> is just an object with each behavior object on its prototype chain and
its options object at the end of the prototype chain.</p>
<h3>Basic Use</h3>
<p>To use <code>can-connect</code>, it's typically best to start out with the most basic
behaviors: <a href="can-connect/data/url/url.html" title="">can-connect/data/url/url</a> and <a href="can-connect/constructor/constructor.html" title="Adds the ability to operate on special types instead of plain JavaScript Objects
and Arrays.">can-connect/constructor/constructor</a>. <a href="can-connect/data/url/url.html" title="">can-connect/data/url/url</a>
connects the "Data Interface" to a restful service. <a href="can-connect/constructor/constructor.html" title="Adds the ability to operate on special types instead of plain JavaScript Objects
and Arrays.">can-connect/constructor/constructor</a> adds
an "Instance Interface" that can create, read, update and delete (CRUD) typed data
using the lower-level "Data Interface".</p>
<p>By <code>typed</code> data we mean data that is more than just plain JavaScript objects. For
example, we might to create <code>todo</code> objects with an <code>isComplete</code> method:</p>
<pre><code class="language-js">var Todo = function(props){
Object.assign(this, props);
};
Todo.prototype.isComplete = function(){
return this.status === "complete";
};
</code></pre>
<p>And, we might want a special list type with <code>completed</code> and <code>active</code> methods:</p>
<pre><code class="language-js">var TodoList = function(todos){
[].push.apply(this, todos);
};
TodoList.prototype = Object.create(Array.prototype);
TodoList.prototype.completed = function(){
return this.filter(function(todo){
return todo.status === "complete";
});
};
TodoList.prototype.active = function(){
return this.filter(function(todo){
return todo.status !== "complete";
});
};
</code></pre>
<p>We can create a connection that connects a restful "/api/todos"
service to <code>Todo</code> instances and <code>TodoList</code> lists like:</p>
<pre><code class="language-js">var todoConnection = connect([constructor, dataUrl],{
url: "/api/todos",
list: function(listData, set){
return new TodoList(listData.data);
},
instance: function(props) {
return new Todo(props);
}
});
</code></pre>
<p>And then use that connection to get a <code>TodoList</code> of <code>Todo</code>s:</p>
<pre><code class="language-js">todoConnection.getList({}).then(function(todos){
var todosEl = document.getElementById("todos-list");
todosEl.innerHTML = "<h2>Active</h2>"+
render(todos.active())+
"<h2>Complete</h2>"+
render(todos.completed());
});
var render = function(todos) {
return "<ul>"+todos.map(function(todo){
return "<li>"+todo.name+
"<input type='checkbox' "+
(todo.isComplete() ? "checked" : "")+"/></li>";
}).join("")+"</ul>";
};
</code></pre>
<p>The following demo shows the result:</p>
<div class='demo_wrapper' data-demo-src='demos/can-connect/basics.html'></div>
<p>This connection also lets you create, update, and destroy a Todo instance as follows:</p>
<pre><code class="language-js">var todo = new Todo({
name: "take out trash"
})
// POSTs to /api/todos name=take out trash
// server returns {id: 5}
todoConnection.save( todo ).then(function(todo){
todo.id //-> 5
todo.name = 'take out garbage'
// PUTs to /api/todos/5 name=take out garbage
// server returns {id: 5, "take out garbage"}
todoConnection.save( todo ).then( function(todo){
// DELETEs to /api/todos/5
// server returns {}
todoConnection.destroy( todo ).then( function(todo){
});
});
});
</code></pre>
<h3>Configure behaviors</h3>
<p>Whenever <code>connect</code> creates a connection, it always adds the <a href="can-connect/base/base.html" title="The base behavior added to every connect behavior.">can-connect/base/base</a>
behavior. This behavior defines configurable options that are used by almost
every other behavior. For example, if your data uses an <code>_id</code> property
to uniquely identify todos, you
can specify this with <a href="can-connect/base/base.idProp.html" title="">idProp</a> like:</p>
<pre><code class="language-js">var todoConnection = connect(["constructor","data-url"],{
url: "/api/todos",
idProp: "_id"
});
</code></pre>
<p>Other behaviors list their configurable options in their own docs page.</p>
<h3>Overwrite behaviors</h3>
<p>If configurable options are not enough, you can overwrite any behavior with your own behavior.</p>
<p>For example, the <code>constructor</code>'s <a href="can-connect/constructor/constructor.updatedInstance.html" title="Updates the instance being updated with the result of connection.updateData.">updatedInstance</a> behavior
sets the instance's properties to match the result of <a href="can-connect/connection.updateData.html" title="Updates a record in the collection.">updateData</a>. But if
the <code>PUT /api/todos/5 name=take out garbage</code> request returned <code>{}</code>, the following would result in
a todo with only an <code>id</code> property:</p>
<pre><code class="language-js">var todo = new Todo({id: 5, name: "take out garbage"})
// PUTs to /api/todos/5 name=take out garbage
// server returns {}
todoConnection.save( todo ).then( function(todo){
todo.id //-> 5
todo.name //-> undefined
});
</code></pre>
<p>The following overwrites the behavior of <code>updateData</code>:</p>
<pre><code class="language-js">var mergeDataBehavior = {
updateData: function(instance, data){
Object.assign(instance, data);
}
}
var todoConnection = connect([
"constructor",
"data-url",
mergeDataBehavior
],{
url: "/api/todos"
});
</code></pre>
<p>You can add your own behavior that overwrite all base behaviors by adding
it to the end of the behaviors list.</p>
<h3>CanJS use</h3>
<p>If you are using CanJS, you can either:</p>
<ul>
<li>use the <a href="can-connect/can/map/map.html" title="Make a connection use a map type.">can-connect/can/map/map</a> behavior that overwrites
many methods and settings to work with <a href="can-define/map/map.html" title="Create observable objects.">can-define/map/map</a> and <a href="can-define/list/list.html" title="Create observable lists.">can-define/list/list</a>.</li>
<li>use the <a href="can-connect/can/super-map/super-map.html" title="Create connection with many of the best behaviors in can-connect and hook it up to
a map.">can-connect/can/super-map/super-map</a> helper to create a connection that bundles "can/map" and
many of the other extensions.</li>
</ul>
<p>Using <a href="can-connect/can/map/map.html" title="Make a connection use a map type.">can-connect/can/map/map</a> to create a connection looks like:</p>
<pre><code class="language-js">var DefineMap = require("can-define/map/map");
var DefineList = require("can-define/list/list");
var Todo = DefineMap.extend({ ... });
Todo.List = DefineList.extend({
"#": Todo
});
var todoConnection = connect([
require("can-connect/data/url/url"),
require("can-connect/can/map/map/map"),
require("can-connect/constructor/constructor"),
require("can-connect/constructor/store/store")
],{
Map: Todo,
url: "/todos"
});
</code></pre>
<p>When you bind on a <code>Todo</code> instance or <code>Todo.List</code> list, they will automatically call
[can.connect/constructor-store.addInstanceReference] and [can.connect/constructor-store.addListReference].</p>
<p>Using <a href="can-connect/can/super-map/super-map.html" title="Create connection with many of the best behaviors in can-connect and hook it up to
a map.">can-connect/can/super-map/super-map</a> to create a connection looks like:</p>
<pre><code class="language-js">var DefineMap = require("can-define/map/map");
var DefineList = require("can-define/list/list");
var Todo = DefineMap.extend({ ... });
Todo.List = DefineList.extend({
"#": Todo
});
var todoConnection = superMap({
Map: Todo,
url: "/todos"
});
</code></pre>
<h3>ReactJS use</h3>
<p>Help us create a special ReactJS behavior that integrates
a connection with React's observable life-cycle. Read more <a href="#section_Otheruse">here</a>.</p>
<h3>Angular use</h3>
<p>Help us create a special AngularJS behavior that integrates
a connection with Angular's observable life-cycle. Read more <a href="#section_Otheruse">here</a>.</p>
<h3>Backbone use</h3>
<p>Help us create a special BackboneJS behavior that integrates
a connection with Backbone's observable life-cycle. Read more <a href="#section_Otheruse">here</a>.</p>
<h3>Other use</h3>
<p>Integrating <code>can-connect</code> with your framework is typically pretty easy. In general,
the pattern involves creating a behavior that integrates with your framework's
observable instances. The <a href="can-connect/can/map/map.html" title="Make a connection use a map type.">can-connect/can/map/map</a>
behavior can serve as a good guide. You'll typically want to implement the following
in your behavior:</p>
<p><code>.instance</code> - Creates the appropriate observable object type.<br />
<code>.list</code> - Creates the appropriate observable array type.<br />
<code>.serializeInstance</code> - Return a plain object out of the observable object type.<br />
<code>.serializeList</code> - Return a plain array out of the observable array type.</p>
<p><code>.createdInstance</code> - Update an instance with data returned from <code>createData</code>.<br />
<code>.updatedInstance</code> - Update an instance with data returned from <code>updateData</code>.<br />
<code>.destroyedInstance</code> - Update an instance with data returned from <code>destroyData</code>.<br />
<code>.updatedList</code> - Update a list with raw data.</p>
<p>And, in most frameworks you know when a particular observable is being used, typically
observed, and when it can be discarded. In those places, you should call:</p>
<p><a href="can-connect/constructor/store/store.addInstanceReference.html" title="Adds a reference to an instance so it can be easily looked up.">addInstanceReference</a> - Call when an instance is being used.<br />
<a href="can-connect/constructor/store/store.deleteInstanceReference.html" title="Removes a reference to an instance by base.id so it can be garbage collected.">deleteInstanceReference</a> - Call when an instance is no longer being used.<br />
<a href="can-connect/constructor/store/store.addListReference.html" title="Adds a reference to a list so it can be easily looked up.">addListReference</a> - Call when a list is being used.<br />
<a href="can-connect/constructor/store/store.deleteListReference.html" title="Removes a reference to a list by base.listSet so it can be garbage collected.">deleteListReference</a> - Called when a list is no longer being used.</p>
<h2>Interfaces</h2>
<p>The following is a list of the most important interface methods and properties implemented
or consumed by the core behaviors.</p>
<h3>Identifiers</h3>
<p><code>.id( props | instance ) -> String</code> - Returns a unique identifier for the instance or raw data.<br />
<code>.idProp -> String="id"</code> - The name of the unique identifier property.<br />
<code>.listSet(list) -> set</code> - Returns the set a list represents.<br />
<code>.listSetProp -> String="__listSet"</code> - The property on a List that contains its set.</p>
<p>Implemented by <a href="can-connect/base/base.html" title="The base behavior added to every connect behavior.">can-connect/base/base</a>.</p>
<h3>Instance Interface</h3>
<p>The following methods operate on instances and lists.</p>
<h4>CRUD methods:</h4>
<p><code>.getList(set) -> Promise<List></code> - retrieve a list of instances.<br />
<code>.getList(set) -> Promise<Instance></code> - retrieve a single instance.<br />
<code>.save(instance) -> Promise<Instance></code> - creates or updates an instance.<br />
<code>.destroy(instance) -> Promise<Instance></code> - destroys an instance.</p>
<p>Implemented by <a href="can-connect/constructor/constructor.html" title="Adds the ability to operate on special types instead of plain JavaScript Objects
and Arrays.">can-connect/constructor/constructor</a>. Overwritten by <a href="can-connect/constructor/store/store.html" title="Supports saving and retrieving lists and instances in a store.">can-connect/constructor/store/store</a>.</p>
<h4>Instance callbacks</h4>
<p><code>.createdInstance(instance, props)</code> - An instance is created.<br />
<code>.updatedInstance(instance, props)</code> - An instance is updated.<br />
<code>.destroyedInstance(instance, props)</code> - An instance is destroyed.<br />
<code>.updatedList(list, updatedListData, set)</code> - A list has been updated.</p>
<p>Implemented by <a href="can-connect/constructor/constructor.html" title="Adds the ability to operate on special types instead of plain JavaScript Objects
and Arrays.">can-connect/constructor/constructor</a>. Overwritten by [data-connect/real-time/real-time],
<a href="can-connect/constructor/callbacks-once/callbacks-once.html" title="Prevents unecessary calls to the instance callback methods.">can-connect/constructor/callbacks-once/callbacks-once</a>.</p>
<h4>Hydrators and Serializers</h4>
<p><code>.instance(props) -> Instance</code> - Creates an instance given raw data.<br />
<code>.list({data: Array<Instance>}) -> List</code> - Creates a list given an array of instances.<br />
<code>.hydrateInstance(props) -> Instance</code> - Provides an instance given raw data.<br />
<code>.hydrateList({ListData}, set) -> List</code> - Provides a list given raw data.<br />
<code>.hydratedInstance(instance)</code> - Called whenever an instance is created in memory.<br />
<code>.hydratedList(list, set)</code> - Called whenever a list is created in memory.<br />
<code>.serializeInstance(instance) -> Object</code> - Returns the serialized form of an instance.<br />
<code>.serializeList(list) -> Array<Object></code> - Returns the serialized form of a list and its instances.</p>
<p>Implemented by <a href="can-connect/constructor/constructor.html" title="Adds the ability to operate on special types instead of plain JavaScript Objects
and Arrays.">can-connect/constructor/constructor</a>. Overwritten by <a href="can-connect/constructor/store/store.html" title="Supports saving and retrieving lists and instances in a store.">can-connect/constructor/store/store</a>,
<a href="can-connect/fall-through-cache/fall-through-cache.html" title="A fall through cache that checks another cacheConnection.">can-connect/fall-through-cache/fall-through-cache</a>.</p>
<h3>Data Interface</h3>
<p>The raw-data connection methods.</p>
<h4>CRUD methods</h4>
<p><code>.getListData(set) -> Promise<ListData></code> - Retrieves list data.<br />
<code>.updateListData(listData[, set]) -> Promise<ListData></code> - Update a list's data.<br />
<code>.getSets() -> Promise<Array<Set>></code> - Returns the sets available to the connection.</p>
<p><code>.getData(params) -> Promise<Object></code> - Retrieves data for a particular item.<br />
<code>.createData(props, cid) -> Promise<props></code> - Creates instance data given the serialized form of the data.
A client ID is passed of the
instance that is being created.<br />
<code>.updateData(props) -> Promise<props></code> - Updates instance data given the
serialized form of the data.<br />
<code>.destroyData(props) -> Promise<props></code> - Destroys an instance given the seralized
form of the data.</p>
<p><code>.clear() -> Promise</code> - Clears all data in the connection.</p>
<p>Implemented by <a href="can-connect/data/url/url.html" title="">can-connect/data/url/url</a>,
<a href="can-connect/data/localstorage-cache/localstorage-cache.html" title="Saves raw data in localStorage.">can-connect/data/localstorage-cache/localstorage-cache</a>, <a href="can-connect/data/memory-cache/memory-cache.html" title="Saves raw data in JavaScript memory that disappears when the page refreshes.">can-connect/data/memory-cache/memory-cache</a>.
Overwritten by <a href="can-connect/cache-requests/cache-requests.html" title="Caches reponse data and uses it to prevent future requests or make future requests smaller.">can-connect/cache-requests/cache-requests</a>, <a href="can-connect/data/combine-requests/combine-requests.html" title="Combines multiple incoming requests into one if possible.">can-connect/data/combine-requests/combine-requests</a>, <a href="can-connect/fall-through-cache/fall-through-cache.html" title="A fall through cache that checks another cacheConnection.">can-connect/fall-through-cache/fall-through-cache</a>.
Consumed by <a href="can-connect/constructor/constructor.html" title="Adds the ability to operate on special types instead of plain JavaScript Objects
and Arrays.">can-connect/constructor/constructor</a>.</p>
<h4>Data Callbacks</h4>
<p><code>.gotListData(listData, set) -> ListaData</code> - List data is retrieved.<br />
<code>.gotData( props, params) -> props</code> - Instance data is retreived.<br />
<code>.createdData( props, params, cid) -> props</code> - An instance's data is created.<br />
<code>.updatedData( props, params) -> props</code> - An instance's data is updated.<br />
<code>.destroyedData( props, params) -> props</code> - An instance's data is destroyed.</p>
<p>Implemented by <a href="can-connect/data/callbacks/callbacks.html" title="Calls callback methods as a result of raw DataInterface requests.">can-connect/data/callbacks/callbacks</a>. Overwritten by <a href="can-connect/data/callbacks-cache/callbacks-cache.html" title="Callback base.cacheConnection methods when data interface callbacks
are called.">can-connect/data/callbacks-cache/callbacks-cache</a>,
<a href="can-connect/real-time/real-time.html" title="Update lists to include or exclude instances based
on set logic.">can-connect/real-time/real-time</a>.</p>
<h4>Response parsers</h4>
<p><code>.parseListData(*) -> ListData</code> - Given the response of getListData, return the right object format.<br />
<code>.parseInstanceData(*) -> props</code> - Given the response of getData, createData, updateData, and destroyData,
return the right object format.</p>
<p>Implemented by <a href="can-connect/data/parse/parse.html" title="Extract response data into a format needed for other extensions.">can-connect/data/parse/parse</a>.</p>
<h4>Store Interface</h4>
<p><code>.addInstanceReference(instance)</code> - Signal that memory-unsafe actions can be performed on the instance.<br />
<code>.deleteInstanceReference(instance)</code> - Signal that memory-unsafe actions should be removed.
<code>.addListReference(list)</code> - Signal that memory-unsafe actions can be performed on the list.<br />
<code>.deleteListReference(list)</code> - Signal that memory-unsafe actions should be removed.</p>
<p>Implemented by <a href="can-connect/constructor/store/store.html" title="Supports saving and retrieving lists and instances in a store.">can-connect/constructor/store/store</a>.</p>
<h4>Real-time Methods</h4>
<p><code>createInstance( props ) -> Promise<instance></code> - Inform the connection an instance has been created.<br />
<code>updateInstance( props ) -> Promise<instance></code> - Inform the connection an instance has been updated.<br />
<code>destroyInstance( props ) -> Promise<instance></code> - Inform the connection an instance has been destroyed.</p>
<p>Implemented by <a href="can-connect/real-time/real-time.html" title="Update lists to include or exclude instances based
on set logic.">can-connect/real-time/real-time</a>.</p>
<h2>Creating Behaviors</h2>
<p>To create your own behavior, call <code>connect.behavior</code> with the name of your behavior and a function that
returns an object that defines the hooks you want to overwrite or provide:</p>
<pre><code class="language-js">connect.behavior("my-behavior", function(baseConnection){
return {
// Hooks here
};
})
</code></pre>
<p>For example, creating a simple localStorage behavior might look like:</p>
<pre><code class="language-js">connect.behavior("localstorage", function(baseConnection){
return {
getData: function(params){
var id = this.id(params);
return new Promise(function(resolve){
var data = localStorage.getItem(baseConnection.name+"