UNPKG

can

Version:

MIT-licensed, client-side, JavaScript framework that makes building rich web applications easy.

343 lines (291 loc) 13.4 kB
<!DOCTYPE html> <!--#################################################################### THIS IS A GENERATED FILE -- ANY CHANGES MADE WILL BE OVERWRITTEN INSTEAD CHANGE: source: [object Object] @page BuildAnApplicationWithData ######################################################################## --> <html lang="en"> <head> <meta charset="utf-8"> <title>CanJS - Build an App with Remote Data</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> &nbsp; </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="BuildAnApplicationWithData.html">Build an App with Remote Data</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>Build an App with Remote Data</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/recipes/build-an-app-with-remote-data.md">source</a></li> <!-- <li><a href="#">download</a></li> --> <!-- <li><a href="#">tests</a></li> --> </ul> </section> <section class="body"> <p>In CanJS, <code>can.Model</code> adds functionality to <code>can.Map</code> to work with data on a server. It enables you to:</p> <ul> <li>Get and modify data from a server</li> <li>Listen to changes made to the data on the server</li> <li>Unify service data with other objects in your application</li> </ul> <p><code>can.Model</code> allows you to access data from a server easily:</p> <pre><code>var Todo = can.Model.extend({ findAll: 'GET /todos', findOne: 'GET /todos/{id}', create: 'POST /todos', update: 'PUT /todos/{id}', destroy: 'DELETE /todos/{id}' },{}); </code></pre> <p>Using <em>any</em> server with a <a href="http://blog.mashape.com/post/60820526317/list-of-40-tutorials-on-how-to-create-an-api"><em>REST</em> interface</a>, <code>can.Model</code> enables create, read, update, and destroy functionality.</p> <h2>Create a Chat Application</h2> <p>To put together a chat application, we’ll use two methods from <code>can.Model</code> to fetch the messages and create new ones:</p> <pre><code>var Message = can.Model({ findAll : 'GET ' + myServerUrl + '/messages', create : 'POST ' + myServerUrl + '/messages' },{}); </code></pre> <p>In a chat component's scope, we will use the <code>Message</code> model to save new messages and observe changes to the Model. <a href="http://canjs.com/docs/can.Model.List.html#sig_newcan_Model_List__models__"><code>new Message.List({})</code></a> is a shortcut to perform the <a href="http://canjs.com/docs/can.Model.findAll.html"><code>findAll</code></a> operation on a <code>can.Model</code> and return a <code>can.List</code>.</p> <pre><code>... scope: { messages: new Message.List({}), newMessage: &quot;&quot; ... </code></pre> <p>The tabs Component used <code>can-click</code> to listen for click events. Since this chat application uses a <code>&lt;form&gt;</code> for sending messages, we’ll use <code>can-submit</code> to specify an event handler.</p> <p>There’s one more helper used in the template: <a href="http://canjs.com/docs/can.view.bindings.can-value.html"><code>can-value</code></a>. This automatically two-way binds the value of an input field to an observable property on the <code>scope</code> of the component (in this case, <code>newMessage</code>).</p> <pre><code>can.Component.extend({ tag: 'chat', template: '&lt;ul id=&quot;messages&quot;&gt;' + '{{#each messages}}' + '&lt;li&gt;{{body}}&lt;/li&gt;' + '{{/each}}' + '&lt;/ul&gt;' + '&lt;form id=&quot;create-message&quot; action=&quot;&quot; can-submit=&quot;submitMessage&quot;&gt;' + '&lt;input type=&quot;text&quot; id=&quot;body&quot; placeholder=&quot;type message here...&quot;' + 'can-value=&quot;newMessage&quot; /&gt;' + '&lt;/form&gt;', ... </code></pre> <p>When <code>submitMessage</code> is called, a new <code>Message</code> is created with <code>new Message()</code>. Since <code>can-value</code> was declared on the <code>input</code> element, <code>newMessage</code> will always be the current text in the <code>input</code> field. The body of the message is fetched from the Component's <code>newMessage</code> attribute when a user submits the form.</p> <p>To save the new message to the server, call <code>save()</code>.</p> <pre><code>submitMessage: function(scope, el, ev){ ev.preventDefault(); new Message({body: this.attr(&quot;newMessage&quot;)}).save(); this.attr(&quot;newMessage&quot;, &quot;&quot;); } </code></pre> <p>Finally, when a new <code>Message</code> is created, the <code>messages</code> list must be updated.</p> <pre><code>events: { '{Message} created': function(construct, ev, message){ this.scope.attr('messages').push(message); } } </code></pre> <p>There are two ways that messages are added: from the current user, or from another user. In the next section, we demonstrate how to use <a href="http://socket.io/">socket.io</a> to update the <code>Message</code> model with messages from other users in real time. Binding to the <code>created</code> event for <strong>all</strong> messages allows us to create a single entry point that pushes new messages to the <code>scope</code>, <a href="http://canjs.com/docs/can.Model.html#section_Listentochangesindata">regardless of where those messages are from.</a></p> <p>When the chat Component is loaded, messages are loaded from the server using <code>can.Model</code> and <code>new Message.List({})</code>. When a new message is submitted:</p> <ol> <li><code>submitMessage</code> is called via the event handler bound by the <code>can-submit</code> attribute</li> <li>a new <code>Message</code> is created and saved to the server</li> <li><code>'{Message} created'</code> detects this change and adds the new message to <code>messages</code></li> <li>The template is automatically updated since <code>messages</code> is an observable <code>can.List</code></li> </ol> <h2>Add real-time functionality</h2> <p>This example uses <a href="http://socket.io/">socket.io</a> to enable real-time functionality. This guide won't go into detail on how to use <code>socket.io</code>, but for real-time chat the application needs two more things.</p> <p>When a message is created on another chat client, <code>socket.io</code> will notify this client by triggering the <code>message-created</code> event, wich will render the new message in the page by adding it to the <code>Message</code> model.</p> <pre><code>var socket = io.connect(myServerUrl); socket.on('message-created', function(message){ new Message(message).created(); }); </code></pre> <p>To keep the <code>created</code> event from firing twice, we modify the <code>create</code> function in the model. If there was simply a <code>return</code> statement, <code>Model</code> would create and fire a <code>create</code> event, which <code>socket</code> is already doing. By returning a <code>Deferred</code>, we prevent firing of one of these events.</p> <pre><code>var Message = can.Model({ findAll : 'GET ' + myServerUrl + '/messages', create : function(attrs) { $.post(myServerUrl + '/messages', attrs); //keep '{Message} created' from firing twice return $.Deferred(); } },{}); </code></pre> <iframe width="100%" height="300" src="http://jsfiddle.net/donejs/afC94/embedded/result,html,js/" allowfullscreen="allowfullscreen" frameborder="0"> </iframe> </section> <script type="text/javascript"> var docObject = {"src":{"path":"docs/can-guides/recipes/build-an-app-with-remote-data.md"},"description":"\n","name":"BuildAnApplicationWithData","title":"Build an App with Remote Data","type":"page","parent":"Recipes","order":6,"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>