background preloader

Backbone patterns

Backbone patterns
Building apps with Backbone.js Here, I try to document the good practices that our team has learned along the way building Backbone applications. This document assumes that you already have some knowledge of Backbone.js, jQuery, and of course, JavaScript itself. Table of contents Thanks

Testing Backbone applications with Jasmine and Sinon – Part 3. Routers and Views – Tinned Fruit Overview This is the third and final part in a series of articles demonstrating how to test a Backbone.js application, employing the Jasmine BDD test framework and the Sinon.JS spying, stubbing and mocking library If you haven’t yet read the first or second parts, take a look now. In this final part, we’ll be looking at some methods for unit testing Backbone routers and views. These object types both present their own unique challenges for testing, but and provide the tools we need to isolate them and fake external code and system dependencies. We will be examining the following: different approaches to testing Backbone routes methods for testing view rendering using DOM fixtures in your specs using the plugin testing view event handlers using fake timers to manipulate timed events Routers router objects are responsible for URL hash routing within your application, and can also be used for initialisation tasks if that’s how you choose to structure your code. Example 1: Testing routes Simple.

Backbone.js Sample App with Backbone.js and Twitter Bootstrap Backbone.js is a lightweight JavaScript framework that provides the basic infrastructure (Model, Collection, View, and Router classes) to bring structure to your Web applications. Twitter Bootstrap is a UI toolkit that provides simple and flexible HTML, CSS, and Javascript to implement popular user interface components and interactions. In other words, Backbone.js and Twitter Bootstrap focus on different areas of your application: core architecture and user interface respectively. Because of their well-defined and non-overlapping scope, Backbone.js and Twitter Bootstrap work well together. The Sample Application To give this combination a try, I put together a new sample application that uses Backbone.js to organize the code, and Twitter Bootstrap to organize the UI. You can run the application here. Backbone Directory is a single page application: index.html is essentially empty. Twitter Bootstrap highlights Backbone.js highlights One-to-Many association. Source Code

Require.JS Usage§ 1 Load JavaScript Files§ 1.1 RequireJS takes a different approach to script loading than traditional <script> tags. While it can also run fast and optimize well, the primary goal is to encourage modular code. As part of that, it encourages using module IDs instead of URLs for script tags. RequireJS loads all code relative to a baseUrl. Or, baseUrl can be set manually via the RequireJS config. RequireJS also assumes by default that all dependencies are scripts, so it does not expect to see a trailing ".js" suffix on module IDs. There may be times when you do want to reference a script directly and not conform to the "baseUrl + paths" rules for finding it. Ends in ".js".Starts with a "/".Contains an URL protocol, like "http:" or "https:". In general though, it is best to use the baseUrl and "paths" config to set paths for module IDs. www/ index.html js/ app/ sub.js lib/ jquery.js canvas.js app.js in index.html: and in app.js: data-main Entry Point§ 1.2 Define a Module§ 1.3

References, Routing, And The Event Aggregator: Coordinating Views In Backbone.js I recently found myself needing to facilitate communication between two backbone views. The first view is a medication – one that is currently being taken by a particular patient. The second view is the add/edit view that allows the patient to either add new medications or edit existing ones. When the edit icon is clicked for an existing medication, the edit form should be populated and the user should be able to edit the medication. Here’s what the screen looks like after I click on the edit icon (the pencil): There are a number of ways to make this work – the most basic of which is to have the views reference each other so that they can either call methods on each other or raise events. References I’ve done this a number of times and it works well. In this simple example, I have an event setup that listens to the edit icon click. In some cases, though, this isn’t really an option – or, it may be an option that would cause a little extra code and work to make sure it works correctly.

Organizing your application using Modules (require.js) - Backbone.js Tutorials Unfortunately Backbone.js does not tell you how to organize your code, leaving many developers in the dark regarding how to load scripts and lay out their development environments. This was quite a different decision to other JavaScript MVC frameworks who were more in favor of setting a development philosophy. Hopefully this tutorial will allow you to build a much more robust project with great separation of concerns between design and code. This tutorial will get you started on combining Backbone.js with AMD (Asynchronous Module Definitions). What is AMD? Asynchronous Module Definitions designed to load modular code asynchronously in the browser and server. This tutorial will use Require.js to implement a modular and organized Backbone.js. I highly recommend using AMD for application development Quick Overview ModularScalableCompiles well(see r.js )Market Adoption( Dojo 1.6 converted fully to AMD ) Why Require.js? Require.js has a great community and it is growing rapidly. Getting started <!

Zepto.js: the aerogel-weight jQuery-compatible JavaScript library Présentation de backbone.js Backbone.js est un cadre applicatif pour les applications à forte teneur en javascript. Backbone.js peut se définir comme un framework MVC mais pas au sens classique du terme. Ici le C représente des Collections d’objets. Le M et le V désignent respectivement les modèles et les vues. Backbone.js ne possède qu’une dépendance ferme, il s’agit de underscore.js, qui est maintenu par la même équipe. Le rôle d’underscore.js est de vous apporter tout un tas de méthodes pour vous simplifier la vie (enumerable, binding, template, comparaison…) sans faire 500ko. Généralement jQuery vient compléter la liste des dépendances finales de l’application, car il y a fort à parier que vous aurez à minima besoin de manipuler le DOM. Quand utiliser Backbone.js Backbone.js est un excellent choix pour les applications dites «single page application», c’est à dire une page principale avec un nombre important d’interactions utilisateur. Pour cela Backbone.js possède son propre routeur. Ce que Backbone.js ne fait pas

Simplify.js - a high-performance JavaScript 2D/3D polyline simplification library Simplify.js (License: BSD, GitHub: mourner / simplify-js, npm: simplify-js) is a tiny high-performance JavaScript polyline simplification library by Vladimir Agafonkin, extracted from Leaflet, a JS interactive maps library of the same author. It uses a combination of Douglas-Peucker and Radial Distance algorithms. Works both on browser and server platforms. Polyline simplification dramatically reduces the number of points in a polyline while retaining its shape, giving a huge performance boost when processing it and also reducing visual noise. For example, it's essential when rendering a 70k-points line chart or a map route in the browser using Canvas or SVG. 73752 points, simplified with tolerance: 0.8 px After simplification: 154 points (~479 times less) Performed in 2.73 ms The test data for the example is actually a ~10700 mile car route from Lisboa, Portugal to Singapore on a world scale, generated by the CloudMade Navigation service based on OpenStreetMap data. points [Array]

Integrating Devise with Backbone.js | Josh Huckabee For the impatient: view the code, or see the demo. Update 30 May 2012: The original version of the application and this article referenced the backbone.modelbinding project by Derick Bailey. Per the readme, that project has been abandoned and I have replaced backbone.modelbinding with the preferred backbone.modelbinder project. All code and referenced samples below have been updated accordingly. Several weeks ago I set out to create a single page web app leveraging Backbone.js on the front end with Ruby on Rails powering the back end. One of the first things I need on almost all new projects is a way to handle user registration, authentication, and authorization. Arguably, doing this is unnecessary as Devise ships with its own UI implementation. To implement the Devise UI in Backbone.js I started by creating 3 Backbone models, one each for authentication, registration, and password retrieval. UserRegistration: UserSession: UserPasswordRecovery: Here is the login view:

stolksdorf.github.com/Parallaxjs/ Parallax.js is a nifty Javascript framework that allows you to easily add sliding page trasitions and parallaxing backgrounds to any project. Very light weight, very cool. Just like fezes. Add accepts either a name and an element, or just an element. With the latter Parallax.js will try to use the element's Id as the name. Pages can be accessed using their name as a property on the Parallax.js object. parallax.add("foo", $("#page1")) .add($("#bar")); parallax.foo; //<- woah! To get a nifty parallaxing background, just set a jQuery element to be Parallax.js's background. parallax.background = $("body"); parallax.scaling = 0.4; //background moves 40% with the pages Some like it fast, some like it slow. parallax.speed = 1200; //In milliseconds of course! The meat and potatoes. parallax.bar.left(); //Bar slides in from the left parallax.foo.top(); //bringing back foo from the top parallax.bar.bottom(IAmBack()); //We got callbacks too ;) function IAmBack(){ alert("I'm back foo!")

Payne Digital Ltd - Bootbox.js - alert, confirm and flexible dialogs for twitter's bootstrap framework UPDATE 01/02/2012: Version 2.0.0 of the Bootbox library is out. Whilst this tutorial is still largely accurate and version 1.1.2 will work with the 1.x series of Twitter's Bootstrap framework, you should check out the updated version here. This article discusses a GitHub repository – feel free to browse the code or follow the project. I’ve been using twitter's bootstrap framework for a number of site builds recently, mainly because it gets me from black-and-white markup to vaguely-presentable websites in a very small amount of time. Dialogs using Twitter Bootstrap You may be wondering why a few wrapper methods around bootstrap's built-in dialog capabilities are either necessary or desirable. Note that this example is purely for demonstration purposes - you probably don't want to show an obtrusive dialog as soon as the page loads! It's important to stress that none of these points are negative, nor are they particularly arduous. Bootbox.js Alerts Which results in the following dialog:

Continuous Integration for Javascript Jenkins is a CI tool that is often used for running tests and code analysis after every code push. There are a lot of benefits that we as a community are not taking advantage of for our web (CSS, JS, etc) code. In this article I’m going to walk you through setting up automated building and testing for a JavaScript project. NOTE: The steps outlined are generally Linux/Mac centric, I don’t go into depth on Windows setup, but it shouldn’t be much different using Cygwin. CI Your JS? Aside from the traditional benefits you see from your compiled code, there are some very compelling reasons: Automate versioning, combining, minifying, and gzipping filesRun automated tests and get reports, keeping the codebase maintainableRun static analysis tools like the closure compiler or jshintAuto-deploy files (to S3, say) if our build passesTag and other special stuff for release buildsAnd that’s not all! Jenkins setup Downloading and running Jenkins is incredibly easy. Nailed it! Prerequisites Setup a CI job

Related: