can
Version:
MIT-licensed, client-side, JavaScript framework that makes building rich web applications easy.
428 lines (357 loc) • 14.6 kB
HTML
<!--####################################################################
THIS IS A GENERATED FILE -- ANY CHANGES MADE WILL BE OVERWRITTEN
INSTEAD CHANGE:
source: [object Object]
@page Observables
######################################################################## -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>CanJS - Observables</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>
</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="Observables.html">Observables</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>Observables</h1>
<div>page</div>
</div>
<section class="description">
</section>
</section>
<section class="on-this-page-table">
</section>
<section class="title-footer">
<ul class="title-links">
<!-- <li><a href="#">docco</a></li> -->
<li><a href="//github.com/canjs/canjs/tree/v3.0.0/docs/can-guides/observables.md">source</a></li>
<!-- <li><a href="#">download</a></li> -->
<!-- <li><a href="#">tests</a></li> -->
</ul>
</section>
<section class="body">
<p>CanJS's observables - <a href="../docs/can.Map.html">can.Map</a>, <a href="../docs/can.List.html">can.List</a>,
and <a href="../docs/can.compute.html">can.compute</a> - let you make changes to data and listen
to those changes. Observables are the subjects in
the <a href="http://en.wikipedia.org/wiki/Observer_pattern">observer pattern</a>. CanJS comes with
three forms of observables:</p>
<ul>
<li><a href="../docs/can.Map.html">can.Map</a> - Used for Objects.</li>
<li><a href="../docs/can.List.html">can.List</a> - Used for Arrays.</li>
<li><a href="../docs/can.compute.html">can.compute</a> - Used for values.</li>
</ul>
<p>can.Map and can.List are often extended to create observable types.
<a href="../docs/can.Model.html">Models</a> and <a href="../docs/can.route.html">can.route</a> are
based on can.Map, and can.Component's <a href="../docs/can.Component.prototype.scope.html">scope</a> is a
can.Map, but observables are useful on their own too.</p>
<p>To create a Map, call <code>new can.Map(obj)</code>. This will give you a map
with the same properties and values as <em>obj</em>. To create a List, call <code>new can.List(array)</code>. This will give you a List with the same elements as
<em>array</em>.</p>
<pre><code>var pagination = new can.Map({page: 1, perPage: 25, count: 1388});
pagination.attr('perPage'); // 25
var hobbies = new can.List(['programming', 'bball', 'party rocking']);
hobbies.attr(2); // 'partying'
</code></pre>
<h2>Manipulating properties</h2>
<p>The <a href="../docs/can.Map.prototype.attr.html">attr</a> method is
used to read and write a property or properties from a Map or List.</p>
<pre><code>pagination.attr('perPage'); // 25
pagination.attr('perPage', 50);
pagination.attr('perPage'); // 50
pagination.attr({page: 10, lastVisited: 1});
pagination.attr(); // {page: 10, perPage: 50, count: 1388, lastVisited: 1}
</code></pre>
<p>Properties can be removed from Observes with <code>removeAttr</code>, which is equivalent
to the <code>delete</code> keyword:</p>
<pre><code>pagination.removeAttr('count');
pagination.attr(); // {page: 10, perPage: 50, lastVisited: 1}
</code></pre>
<h2>Listening to events</h2>
<p>When a property on a Map is changed with <code>attr</code>, the Map will emit two
events: A <em>change</em> event and an event with the same name as the property that
was changed. You can listen for these events by using
<a href="../docs/can.Map.prototype.bind.html">bind</a>:</p>
<pre><code>paginate.bind('change', function(event, attr, how, newVal, oldVal) {
attr; // 'perPage'
how; // 'set'
newVal; // 30
oldVal; // 50
});
paginate.bind('perPage', function(event, newVal, oldVal) {
newVal; // 30
oldVal; // 50
});
paginate.attr('perPage', 30);
</code></pre>
<p>You can similarly stop listening to these events by using
<a href="../docs/can.Map.prototype.unbind.html">unbind</a>:</p>
<pre><code>var timesChanged = 0,
changeHandler = function() { timesChanged++; },
obs = new can.Map({value: 10});
obs.bind('change', changeHandler);
obs.attr('value', 20);
timesChanged; // 1
obs.unbind('change', changeHandler);
obs.attr('value', 30);
timesChanged; // 1
</code></pre>
<h2>Iterating though a Map</h2>
<p>If you want to iterate through the properties on a Map, use <code>each</code>:</p>
<pre><code>paginate.each(function(val, key) {
console.log(key + ': ' + val);
});
// The console shows:
// page: 10
// perPage: 30
// lastVisited: 1
</code></pre>
<h2>Extending a Map</h2>
<p>Extending a can.Map (or can.List) lets you create custom observable
types. The following extends can.Map to create a Paginate type that
has a <code>.next()</code> method to change its state:</p>
<pre><code>Paginate = can.Map.extend({
limit: 100,
offset: 0,
count: Infinity,
page: function() {
return Math.floor(this.attr('offset') / this.attr('limit')) + 1;
},
next: function() {
this.attr('offset', this.attr('offset') + this.attr('limit') );
}
});
var pageInfo = new Paginate();
pageInfo.attr("offset") //-> 0
pageInfo.next();
pageInfo.attr("offset") //-> 100
pageInfo.page() //-> 2
</code></pre>
<h2>Observable Arrays</h2>
<p>As mentioned above, CanJS also provides observable arrays with can.List.
can.List inherits from can.Map, so a List works much the same way an
Map does, with the addition of several methods useful for working with
arrays:</p>
<ul>
<li><a href="../docs/can.List.prototype.indexOf.html">indexOf</a>, which looks for an item in a
List.</li>
<li><a href="../docs/can.List.prototype.pop.html">pop</a>, which removes the last item from a
List.</li>
<li><a href="../docs/can.List.prototype.push.html">push</a>, which adds an item to the end of a
List.</li>
<li><a href="../docs/can.List.prototype.shift.html">shift</a>, which removes the first item from
a List.</li>
<li><a href="../docs/can.List.prototype.unshift.html">unshift</a>, which adds an item to the front
of a List.</li>
<li><a href="../docs/can.List.prototype.splice.html">splice</a>, which removes and inserts items
anywhere in a List.</li>
</ul>
<p>When these methods are used to modify a List, the appropriate events are
emitted. See <a href="../docs/can.List.html">the API for Lists</a> for more
information on the arguments passed to those event handlers.</p>
<h2>Computed values</h2>
<p>CanJS also provides a way to make values themselves observable with
<a href="../docs/can.compute.html">can.compute</a>. A Compute represents a dynamic value
that can be read, set, and listened to just like a Map.</p>
<h3>Static Computes</h3>
<p>A simple static Compute contains a single value, and is created by calling
<code>can.compute(value)</code>. This value can be read, set, and listened to:</p>
<pre><code>// create a Compute
var age = can.compute(25),
previousAge = 0;
// read the Compute's value
age(); // 25
// listen for changes in the Compute's value
age.bind('change', function(ev, newVal, oldVal) {
previousAge = oldVal;
});
// set the Compute's value
age(26);
age(); // 26
previousAge; // 25
</code></pre>
<h3>Composite Computes</h3>
<p>Computes can also be used to generate a unique value based on values derived
from other observable properties. This type of compute is created by calling
<code>can.compute(getterFunction)</code>. When the observable properties that the compute is
derived from change, the value of the compute changes:</p>
<pre><code>var name = new can.Map({
first: 'Alice',
last: 'Liddell'
});
var fullName = can.compute(function() {
// We use attr to read the values
// so the compute knows what to listen to.
return name.attr('first') + ' ' + name.attr('last');
});
var previousName = '';
fullName(); // 'Alice Liddell'
fullName.bind('change', function(ev, newVal, oldVal) {
previousName = oldVal;
});
name.attr({
first: 'Allison',
last: 'Wonderland'
});
fullname(); // 'Allison Wonderland'
previousName; // 'Alice Liddell'
</code></pre>
<p>Since the value of the Compute is cached any time a derived value is
changed, reading the value is fast.</p>
<h3>Converted Computes</h3>
<p>Computes are also useful for creating links to properties within Observes. One
of the most frequent examples of this is when converting from one unit to
another.</p>
<pre><code>// progress ranges from 0 to 1.
var project = new can.Map({ progress: 0.3 });
var progressPercentage = can.compute(function(newVal) {
if(newVal !== undefined) {
// set a value
project.attr('progress', newVal / 100);
} else {
// get the value
return project.attr('progress') * 100;
}
});
percentage(); // 30
// Setting percentage...
percentage(75);
// ...updates project.progress!
project.attr('progress'); // .75
</code></pre>
</section>
<script type="text/javascript">
var docObject = {"src":{"path":"docs/can-guides/observables.md"},"description":"\n","name":"Observables","title":"Observables","type":"page","parent":"Tutorial","order":1,"comment":" ","pathToRoot":".."};
</script>
</article>
<footer><p>CanJS is part of <a href="http://donejs.com" target="_blank">DoneJS</a>. Created and maintained by the core <a href="https://donejs.com/About.html#section=section_Team" target="_blank">DoneJS team</a> and <a href="http://bitovi.com" target="_blank">Bitovi</a>. <strong>Currently 3.0.0.</strong></p></footer>
</div>
</div>
</div>
<script>
steal = {
instantiated: {
"bundles/bit-docs-site/static.css!$css" : null
}
};
</script>
<script type='text/javascript' data-main="bit-docs-site/static" src="./static/node_modules/steal/steal.production.js"></script>
<script async defer src="https://buttons.github.io/buttons.js"></script>
</body>
</html>