can
Version:
MIT-licensed, client-side, JavaScript framework that makes building rich web applications easy.
894 lines (681 loc) • 33.8 kB
HTML
<!--####################################################################
THIS IS A GENERATED FILE -- ANY CHANGES MADE WILL BE OVERWRITTEN
INSTEAD CHANGE:
source: [object Object]
@page can-core
######################################################################## -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>CanJS - Core</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="current
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="
">
<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>
</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 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>Core</h1>
<div>page</div>
</div>
<section class="description">
<p>The best, most hardened and generally useful libraries in CanJS.</p>
</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-canjs/can-core.md">source</a></li>
<!-- <li><a href="#">download</a></li> -->
<!-- <li><a href="#">tests</a></li> -->
</ul>
</section>
<section class="body">
<h2>Use</h2>
<p>CanJS's core libraries are the modules most commonly used to build web
applications. Each module is part of an independent package, so you
should install the ones you use directly:</p>
<pre><code>npm install can-define can-set can-connect can-component can-stache can-route --save
</code></pre>
<p>Lets explore each one a bit more.</p>
<h2>can-compute</h2>
<p><a href="can-compute.html" title="Create an observable value.">can-compute</a>s represent an observable value. A compute can contain its
own value and notify listeners of changes like:</p>
<pre><code class="language-js">var compute = require("can-compute");
var name = compute("Justin");
// read the value
name() //-> "Justin"
name.on("change", function(ev, newVal, oldVal){
newVal //-> "Matthew"
oldVal //-> "Justin"
});
name("Matthew");
</code></pre>
<p>More commonly, a compute derives its value from other observables. The following
<code>info</code> compute derives its value from a <code>person</code> map, <code>hobbies</code> list, and <code>age</code>
compute:</p>
<pre><code class="language-js">var DefineMap = require("can-define/map/map"),
DefineList = require("can-define/list/list"),
compute = require("can-compute");
var person = new DefineMap({first: "Justin", last: "Meyer"}),
hobbies = new DefineList(["js","bball"]),
age = compute(33);
var info = compute(function(){
return person.first +" "+ person.last+ " is "+age()+
"and like "+hobbies.join(", ")+".";
});
info() //-> "Justin Meyer is 33 and likes js, bball."
info.on("change", function(ev, newVal){
newVal //-> "Justin Meyer is 33 and likes js."
});
hobbies.pop();
</code></pre>
<h2>can-define</h2>
<p><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> allow you to create observable
maps and lists with well defined properties. You can
<a href="can-define.types.propDefinition.html" title="Defines the type, initial value, and get, set, and serialize behavior for an
observable property. These behaviors can be specified with as an Object, String,
Constructor function, Array, a getter expression, or setter expression.">define a property's type initial value, enumerability, getter-setters and much more</a>.
For example, you can define the behavior of a <code>Todo</code> type and a <code>TodoList</code> type as follows:</p>
<pre><code class="language-js">var DefineMap = require("can-define/map/map");
var DefineList = require("can-define/list/list");
var Todo = DefineMap.extend({ // A todo has a:
name: "string", // .name that's a string
complete: { // .complete that's
type: "boolean", // a boolean
value: false // initialized to false
},
dueDate: "date", // .dueDate that's a date
get isPastDue(){ // .pastDue that returns if the
return new Date() > this.dueDate; // dueDate is before now
},
toggleComplete: function(){ // .toggleComplete method that
this.complete = !this.complete; // changes .complete
}
});
var TodoList = DefineList.extend({ // A list of todos:
"#": Todo, // has numeric properties
// as todos
get completeCount(){ // has .completeCount that
return this.filter("complete") // returns # of
.length; // complete todos
}
});
</code></pre>
<p>This allows you to create a Todo, read its properties, and
call back its methods like:</p>
<pre><code class="language-js">var dishes = new Todo({
name: "do dishes",
// due yesterday
dueDate: new Date() - 1000 * 60 * 60 * 24
});
dishes.name //-> "do dishes"
dishes.isPastDue //-> true
dishes.complete //-> false
dishes.toggleComplete()
dishes.complete //-> true
</code></pre>
<p>And it allows you to create a <code>TodoList</code>, access its items and properties
like:</p>
<pre><code class="language-js">var todos = new TodoList( dishes, {name: "mow lawn", dueDate: new Date()});
todos.length //-> 2
todos[0].complete //-> true
todos.completeCount //-> 1
</code></pre>
<p>These observables provide the foundation
for data connection (models), view-models and even routing in your application.</p>
<h2>can-set</h2>
<p><a 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> models a service layer's behavior as a <a href="can-set.Algebra.html" title="Perform set logic with an awareness of how certain properties represent a set.">set.Algebra</a>. Once modeled, other libraries such as <a 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> or <a href="can-fixture.html" title="can-fixture intercepts an AJAX request and simulates the response with a file or function.">can-fixture</a> can
add a host of functionality like: real-time behavior, performance optimizations, and
simulated service layers.</p>
<p>A <code>todosAlgebra</code> set algebra for a <code>GET /api/todos</code> service might look like:</p>
<pre><code class="language-js">var set = require("can-set");
var todosAlgebra = new set.Algebra(
// specify the unique identifier property on data
set.prop.id("_id"),
// specify that completed can be true, false or undefined
set.prop.boolean("complete"),
// specify the property that controls sorting
set.prop.sort("orderBy")
)
</code></pre>
<p>This assumes that the service:</p>
<ul>
<li>Returns data where the unique property name is <code>_id</code>:
<pre><code class="language-js">GET /api/todos
-> [{_id: 1, name: "mow lawn", complete: true},
{_id: 2, name: "do dishes", complete: false}, ...]
</code></pre></li>
<li>Can filter by a <code>complete</code> property:
<pre><code class="language-js">GET /api/todos?complete=false
-> [{_id: 2, name: "do dishes", complete: false}, ...]
</code></pre></li>
<li>Sorts by an <code>orderBy</code> property:
<pre><code class="language-js">GET /api/todos?orderBy=name
-> [{_id: 2, name: "do dishes", complete: false},
{_id: 1, name: "mow lawn", complete: true}]
</code></pre></li>
</ul>
<p>In the next section will use <code>todoAlgebra</code> to build a model with <a 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>.</p>
<h2>can-connect</h2>
<p><a 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> connects a data type, typically a <code>DefineMap</code> and its <code>DefineList</code>,
to a service layer. This is often done via the
<a 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-connect/can/base-map/base-map</a> module which bundles many common behaviors
into a single api:</p>
<pre><code class="language-js">var baseMap = require("can-connect/can/base-map/base-map"),
DefineMap = require("can-define/map/map"),
DefineList = require("can-define/list/list"),
set = require("can-set");
var Todo = DefineMap.extend({
...
});
var TodosList = DefineMap.extend({
"#": Todo,
...
});
var todosAlgebra = new set.Algebra({
...
});
var connection = baseMap({
url: "/api/todos",
Map: Todo,
List: TodoList,
algebra: todosAlgebra,
name: "todo"
});
</code></pre>
<p><code>baseMap</code> extends the <code>Map</code> type, in this case, <code>Todo</code>, with
the ability to make requests to the service layer.</p>
<ul>
<li><a href="can-connect/can/map/map.getList.html" title="Gets a list of instances of the map type.">Get a list</a> of Todos
<pre><code class="language-js">Todo.getList({complete: true}).then(function(todos){})
</code></pre></li>
<li><a href="can-connect/can/map/map.get.html" title="Gets an instance of the map type.">Get</a> a single Todo
<pre><code class="language-js">Todo.get({_id: 6}).then(function(todo){})
</code></pre></li>
<li><a href="can-connect/can/map/map.prototype.save.html" title="Persists the map's data to the connection.">Create</a> a Todo
<pre><code class="language-js">var todo = new Todo({name: "do dishes", complete: false})
todo.save().then(function(todo){})
</code></pre></li>
<li><a href="can-connect/can/map/map.prototype.save.html" title="Persists the map's data to the connection.">Update</a> an <a href="can-connect/can/map/map.prototype.isNew.html" title="Returns if the map has not been persisted.">already created</a> Todo
<pre><code class="language-js">todo.complete = true;
todo.save().then(function(todo){})
</code></pre></li>
<li><a href="can-connect/can/map/map.prototype.destroy.html" title="Delete's the instance with the connection.">Delete</a> a Todo
<pre><code class="language-js">todo.destroy().then(function(todo){})
</code></pre></li>
</ul>
<p><a 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> is also middleware, so custom connections can
be assembled too:</p>
<pre><code class="language-js">var base = require("can-connect/base/base");
var dataUrl = require("can-connect/data-url/data-url");
var constructor = require("can-connect/constructor/constructor");
var map = require("can-connect/can/map/map");
var options = {
url: "/api/todos",
Map: Todo,
List: TodoList,
algebra: todosAlgebra,
name: "todo"
}
var connection = map(constructor(dataUrl(base(options))));
</code></pre>
<h2>can-stache</h2>
<p><a href="can-stache.html" title="Live binding Mustache and Handlebars-compatible templates.">can-stache</a> provides live binding mustache and handlebars syntax. While
templates should typically be loaded with a module loader like <a href="steal-stache.html" title="A StealJS extension that allows stache templates as dependencies.">steal-stache</a>,
you can create a template programmatically that lists out todos within a
promise loaded from <code>Todo.getList</code> like:</p>
<pre><code class="language-js">var stache = require("can-stache");
// Creates a template
var template = stache(
"<ul>"+
"{{#if todos.isPending}}<li>Loading...</li>{{/if}}"+
"{{#if todos.isResolved}}"+
"{{#each todos.value}}"+
"<li class='{{#complete}}complete{{/complete}}'>{{name}}</li>"+
"{{else}}"+
"<li>No todos</li>"+
"{{/each}}"+
"{{/if}}"+
"</ul>");
// Calls the template with some data
var frag = template({
todos: Todo.getList({})
});
// Inserts the result into the page
document.body.appendChild(frag);
</code></pre>
<p><a href="can-stache.html" title="Live binding Mustache and Handlebars-compatible templates.">can-stache</a> templates use magic tags like <code>{{}}</code> to control what
content is rendered. The most common forms of those magic tags are:</p>
<ul>
<li><a href="can-stache.tags.escaped.html" title="Insert the value of the expression into the output of the template.">{{key}}</a> - Insert the value at <code>key</code> in the page. If <code>key</code> is a function or helper, run it and insert the result.</li>
<li><a href="can-stache.tags.section.html" title="Renders a subsection one or more times depending on the type of expression
or the expression's return value.">{{#key}}...{{/key}}</a> - Render the content between magic tags based on some criteria.</li>
</ul>
<p><a href="can-stache.html" title="Live binding Mustache and Handlebars-compatible templates.">can-stache</a> templates return document fragments that update whenever
their source data changes.</p>
<h2>can-component</h2>
<p><a href="can-component.html" title="Create a custom element that can be used to manage widgets or application logic.">can-component</a> creates custom elements with unit-testable view models. It
combines a view model created by <a href="can-define/map/map.html" title="Create observable objects.">can-define/map/map</a> with a template
created by <a href="can-stache.html" title="Live binding Mustache and Handlebars-compatible templates.">can-stache</a>.</p>
<pre><code class="language-js">var Component = require("can-component");
var DefineMap = require("can-define/map/map");
var stache = require("can-stache");
// Defines the todos-list view model
var TodosListVM = DefineMap.extend({
// An initial value that is a promise containing the
// list of all todos.
todos: {
value: function(){
return Todo.getList({});
}
},
// A method that toggles a todo's complete property
// and updates the todo on the server.
toggleComplete: function(todo){
todo.complete = !todo.complete;
todo.save();
}
});
Component.extend({
tag: "todos-list",
ViewModel: TodosVM,
view: stache(
"<ul>"+
"{{#if todos.isPending}}<li>Loading...</li>{{/if}}"+
"{{#if todos.isResolved}}"+
"{{#each todos.value}}"+
"<li ($click)='toggleComplete(.)'"+
"class='{{#complete}}complete{{/complete}}'>{{name}}</li>"+
"{{else}}"+
"<li>No todos</li>"+
"{{/each}}"+
"{{/if}}"+
"</ul>");
});
</code></pre>
<h2>can-stache-bindings</h2>
<p><a href="can-stache-bindings.html" title="Provides template event, one-way, and two-way bindings.">can-stache-bindings</a> provides <a href="can-view-callbacks.attr.html" title="Register custom behavior for an attribute.">custom attributes</a> for
<a href="can-stache.html" title="Live binding Mustache and Handlebars-compatible templates.">can-stache</a> event and data bindings.</p>
<p>Bindings look like:</p>
<ul>
<li><code>(event)="key()"</code> for <a href="can-stache-bindings.event.html" title="Response to events on elements or component ViewModels.">event binding</a>.</li>
<li><code>{prop}="key"</code> for <a href="can-stache-bindings.toChild.html" title="One-way bind a value in the parent scope to the viewModel.">one-way binding to a child</a>.</li>
<li><code>{^prop}="key"</code> for <a href="can-stache-bindings.toParent.html" title="One-way bind a value in the current viewModel to the parent scope.">one-way binding to a parent</a>.</li>
<li><code>{(prop)}="key"</code> for <a href="can-stache-bindings.twoWay.html" title="Two-way bind a value in the viewModel or the element to the parent scope.">two-way binding</a>.</li>
</ul>
<p>Adding <code>$</code> to a binding like <code>($event)="key()"</code> changes the binding from the viewModel to the element's attributes or properties.</p>
<p><a href="can-stache-bindings.event.html" title="Response to events on elements or component ViewModels.">Event</a> binding examples:</p>
<pre><code class="language-html"><!-- calls `toggleComplete` when the li is clicked -->
<li ($click)="toggleComplete(.)"/>
<!-- calls `resetData` when cancel is dispatched on `my-modal`'s view model -->
<my-modal (cancel)="resetData()"/>
</code></pre>
<p><a href="can-stache-bindings.toChild.html" title="One-way bind a value in the parent scope to the viewModel.">One-way to child</a> examples:</p>
<pre><code class="language-html"><!-- updates input's `checked` property with the value of complete -->
<input type="checkbox" {$checked}="complete"/>
<!-- updates `todo-lists`'s `todos` property with the result of `getTodos`-->
<todos-list {todos}="getTodos(complete=true)"/>
</code></pre>
<p><a href="can-stache-bindings.toChild.html" title="One-way bind a value in the parent scope to the viewModel.">One-way to parent</a> examples:</p>
<pre><code class="language-html"><!-- updates `complete` with input's `checked` property -->
<input type="checkbox" {^$checked}="complete"/>
<!-- updates `todosList` with `todo-lists`'s `todos` property -->
<todos-list {^todos}="todosList"/>
</code></pre>
<p><a href="can-stache-bindings.twoWay.html" title="Two-way bind a value in the viewModel or the element to the parent scope.">Two-way</a> examples:</p>
<pre><code class="language-html"><!-- Updates the input's `value` with `name` and vice versa -->
<input type="text" {($value)}="name"/>
<!-- Updates `date-picker`'s `date` with `dueDate` and vice versa -->
<date-picker {(date)}="dueDate"/>
</code></pre>
<h2>can-route and can-route-pushstate</h2>
<p><a href="can-route.html" title="Manage browser history and client state by synchronizing the window.location.hash with a map.">can-route</a> connects a <code>DefineMap</code>'s properties to values in the
url. Create a map type, [canjs/doc/can-route.map connect it to the url], and <a href="can-route.ready.html" title="Initializes can-route.">begin routing</a> like:</p>
<pre><code class="language-js">var route = require("can-route");
var DefineMap = require("can-define/map/map");
var AppViewModel = DefineMap.extend({
seal: false
},{
// Sets the default type to string
"#": "string",
todoId: "string",
todo: {
get: function(){
if(this.todoId) {
return Todo.get({_id: this.todoId})
}
}
}
});
var appViewModel = new AppViewModel();
route.map(appViewModel);
route.ready();
</code></pre>
<p>When the url changes, to something like <code>#!&todoId=5</code>, so will the
<code>appViewModel</code>'s <code>todoId</code> and <code>todo</code> property:</p>
<pre><code class="language-js">appViewModel.todoId //-> "5"
appViewModel.todo //-> Promise<Todo>
</code></pre>
<p>Similarly, if <code>appViewModel</code>'s <code>todoId</code> is set like:</p>
<pre><code class="language-js">appViewModel.todoId = 6;
</code></pre>
<p>The hash will be updated:</p>
<pre><code class="language-js">window.location.hash //-> "#!&todoId=6"
</code></pre>
<p>The <code>route</code> function can be used to specify pretty routing rules that
translate property changes to a url and a url to property changes. For example,</p>
<pre><code class="language-js">// a route like:
route("todo/{todoId}");
// and a hash like:
window.location.hash = "#!todo/7";
// produces an appViewModel like:
appViewModel.serialize() //-> {route: "todo/{todoId}", todoId: "7"}
</code></pre>
<p><a 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> adds <a href="https://developer.mozilla.org/en-US/docs/Web/API/History_API">pushstate</a> support. It
mixes in this behavior so you just need to import the module:</p>
<pre><code class="language-js">var route = require("can-route");
require("can-route-pushstate");
</code></pre>
<h2>Want to learn more?</h2>
<p>If you haven't already, checkout the <a 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> page on how to learn CanJS. Specifically, you'll
want to checkout the <a href="guides/chat.html" title="This guide walks through building real time chat application with CanJS's Core libraries. It takes about 30 minutes to complete.">Chat Guide</a> and <a href="guides/todomvc.html" title="This guide walks through building a slightly modified version of TodoMVC with CanJS's Core libraries and can-fixture. It takes about 1 hour to complete.">TodoMVC Guide</a> to learn the basics of using CanJS's
core libraries. After that, checkout the <a href="guides/api.html" title="This page walks through how to use and understand CanJS's API documentation.">API Guide</a> on how to use and learn from these API docs.</p>
</section>
<script type="text/javascript">
var docObject = {"src":{"path":"docs/can-canjs/can-core.md"},"description":"The best, most hardened and generally useful libraries in CanJS. \n","name":"can-core","title":"Core","type":"page","parent":"canjs","outline":"0","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>