Commit e82b3c20 authored by Addy Osmani's avatar Addy Osmani

Merge pull request #633 from anantn/firebase

Realtime: Addition for Firebase as a realtime framework
parents 2ec5dc11 6defd806
......@@ -225,7 +225,7 @@
</ul>
<hr>
<h2>Real-time</h2>
<ul class="applist">
<ul class="applist amd">
<li class="labs">
<a href="http://todomvcapp.meteor.com" data-source="http://meteor.com" data-content="Meteor is an ultra-simple environment for building modern websites.A Meteor application is a mix of JavaScript that runs inside a client web browser, JavaScript that runs on the Meteor server inside a Node.js container, and all the supporting HTML fragments, CSS rules, and static assets. Meteor automates the packaging and transmission of these different components. And, it is quite flexible about how you choose to structure those components in your file tree.">Meteor</a>
</li>
......@@ -235,6 +235,9 @@
<li class="labs">
<a href="https://github.com/tastejs/todomvc/blob/gh-pages/labs/architecture-examples/socketstream/readme.md" data-source="http://www.socketstream.org" data-content="SocketStream is a fast, modular Node.js web framework dedicated to building realtime single-page apps">SocketStream</a>
</li>
<li class="routing labs">
<a href="labs/architecture-examples/firebase-angular/" data-source="https://www.firebase.com" data-content="Firebase is a scalable realtime backend that lets you build apps without managing servers. Firebase persists and updates JSON data in realtime and is best used in combination with a JavaScrpt MV* framework such as AngularJS or Backbone.">Firebase + AngularJS</a>
</li>
<!--
// Link is currently not working.
<li class="routing labs">
......
{
"name": "todomvc-angular",
"version": "0.0.0",
"dependencies": {
"angular": "~1.0.7",
"angular-fire": "~0.2.0",
"todomvc-common": "~0.1.4"
},
"devDependencies": {
"angular-mocks": "~1.0.5"
}
}
{
"name": "angular-fire",
"version": "0.2.0",
"main": [
"./angularFire.js",
"./angularfire.min.js"
],
"ignore": [
"Makefile",
"tests",
"README.md",
".travis.yml"
],
"dependencies": {
"angular": "1.0.7"
},
"gitHead": "171b80650f6501143878d2ec50e57f466c31e7d8",
"readme": "AngularFire\n===========\nAngularFire is an officially supported [AngularJS](http://angularjs.org/) binding\nfor [Firebase](http://www.firebase.com/?utm_medium=web&utm_source=angularFire).\nFirebase is a full backend so you don't need servers to build your Angular app!\n\nThe bindings let you associate a Firebase URL with a model (or set of models),\nand they will be transparently kept in sync across all clients currently using\nyour app. The 2-way data binding offered by AngularJS works as normal, except\nthat the changes are also sent to all other clients instead of just a server.\n\n### Live Demo: <a target=\"_blank\" href=\"http://firebase.github.io/angularFire/examples/chat/\">Simple chat room</a>.\n### Live Demo: <a target=\"_blank\" href=\"http://firebase.github.io/angularFire/examples/todomvc/\">Real-time TODO app</a>.\n\n[![Build Status](https://travis-ci.org/firebase/angularFire.png)](https://travis-ci.org/firebase/angularFire)\n\nUsage\n-----\nInclude both firebase.js and angularFire.js in your application.\n\n```html\n<script src=\"https://cdn.firebase.com/v0/firebase.js\"></script>\n<script src=\"angularFire.js\"></script>\n```\n\nAdd the module `firebase` as a dependency to your app module:\n\n```js\nvar myapp = angular.module('myapp', ['firebase']);\n```\n\nYou now have two options.\n\nOption 1: Implicit synchronization\n----------------------------------\nThis method is great if you want to implicitly synchronize a model with Firebase.\nAll local changes will be automatically sent to Firebase, and all remote changes\nwill instantly update the local model.\n\nSet `angularFire` as a service dependency in your controller:\n\n```js\nmyapp.controller('MyCtrl', ['$scope', 'angularFire',\n function MyCtrl($scope, angularFire) {\n ...\n }\n]);\n```\n\nBind a Firebase URL to any model in `$scope`. The fourth argument is the type\nof model you want to use (can be any JavaScript type, you mostly want a\ndictionary or array):\n\n```js\nvar url = 'https://<my-firebase>.firebaseio.com/items';\nvar promise = angularFire(url, $scope, 'items', []);\n```\n\nUse the model in your markup as you normally would:\n\n```html\n<ul ng-controller=\"MyCtrl\">\n <li ng-repeat=\"item in items\">{{item.name}}: {{item.desc}}</li>\n</ul>\n```\n\nData from Firebase is loaded asynchronously, so make sure you edit the model\n*only after the promise has been fulfilled*. You can do this using the `then`\nmethod (See the\n[Angular documentation on $q](http://docs.angularjs.org/api/ng.$q)\nfor more on how promises work).\n\nPlace all your logic that will manipulate the model like this:\n\n```js\npromise.then(function() {\n // Add a new item by simply modifying the model directly.\n $scope.items.push({name: \"Firebase\", desc: \"is awesome!\"});\n // Or, attach a function to $scope that will let a directive in markup manipulate the model.\n $scope.removeItem = function() {\n $scope.items.splice($scope.toRemove, 1);\n $scope.toRemove = null;\n };\n});\n```\n\nSee the source for the\n[controller behind the demo TODO app](https://github.com/firebase/angularFire/blob/gh-pages/examples/todomvc/js/controllers/todoCtrl.js)\nfor a working example of this pattern.\n\nOption 2: Explicit synchronization\n---------------------------------- \nThis method is great if you want control over when local changes are\nsynchronized to Firebase. Any changes made to a model won't be synchronized\nautomatically, and you must invoke specific methods if you wish to update the\nremote data. All remote changes will automatically appear in the local model\n(1-way synchronization).\n\nSet `angularFireCollection` as a service dependency in your controller:\n\n```js\nmyapp.controller('MyCtrl', ['$scope', 'angularFireCollection',\n function MyCtrl($scope, angularFireCollection) {\n ...\n }\n]);\n```\n\nCreate a collection at a specified Firebase URL and assign it to a model in `$scope`:\n\n```js\n$scope.items = angularFireCollection(url);\n```\n\nUse the model as you normally would in your markup:\n\n```html\n<ul ng-controller=\"MyCtrl\">\n <li ng-repeat=\"item in items\">{{item.name}}: {{item.desc}}</li>\n</ul>\n```\n\nYou can bind specific functions if you wish to add, remove or update objects in\nthe collection with any Angular directive:\n\n```html\n<form ng-submit=\"items.add(item)\">\n <input type=\"text\" ng-model=\"item.name\" placeholder=\"Name\" required/>\n <input type=\"text\" ng-model=\"item.desc\" placeholder=\"Description\"/>\n</form>\n```\n\nYou can do the same with the `remove` and `update` methods.\n\nSee the source for the\n[controller behind the demo chat app](https://github.com/firebase/angularFire/blob/gh-pages/examples/chat/app.js)\nfor a working example of this pattern.\n\nDevelopment\n-----------\nIf you'd like to hack on AngularFire itself, you'll need\n[UglifyJS](https://github.com/mishoo/UglifyJS2) and\n[CasperJS](https://github.com/n1k0/casperjs):\n\n```bash\nnpm install uglifyjs -g\nbrew install casperjs\n```\n\nA Makefile is included for your convenience:\n\n```bash\n# Run tests\nmake test\n# Minify source\nmake minify\n```\n\nLicense\n-------\n[MIT](http://firebase.mit-license.org).\n",
"readmeFilename": "README.md",
"_id": "angular-fire@0.2.0",
"description": "AngularFire =========== AngularFire is an officially supported [AngularJS](http://angularjs.org/) binding for [Firebase](http://www.firebase.com/?utm_medium=web&utm_source=angularFire). Firebase is a full backend so you don't need servers to build your Angular app!",
"repository": {
"type": "git",
"url": "git://github.com/firebase/angularFire.git"
}
}
\ No newline at end of file
{
"name": "angular-mocks",
"version": "1.0.7",
"main": "./angular-mocks.js",
"dependencies": {
"angular": "1.0.7"
},
"gitHead": "73ba0b247c919472906ac3fbbe8fa5cce6a853cd",
"readme": "bower-angular-mocks\n===================\n\nangular-mocks.js bower repo",
"readmeFilename": "README.md",
"_id": "angular-mocks@1.0.7",
"description": "bower-angular-mocks ===================",
"repository": {
"type": "git",
"url": "git://github.com/angular/bower-angular-mocks.git"
}
}
\ No newline at end of file
{
"name": "angular",
"version": "1.0.7",
"main": "./angular.js",
"dependencies": {},
"gitHead": "6c0e81da2073f3831e32ed486d5aabe17bfc915f",
"_id": "angular@1.0.7",
"readme": "ERROR: No README.md file found!",
"description": "ERROR: No README.md file found!",
"repository": {
"type": "git",
"url": "git://github.com/angular/bower-angular.git"
}
}
\ No newline at end of file
(function () {
'use strict';
// Underscore's Template Module
// Courtesy of underscorejs.org
var _ = (function (_) {
_.defaults = function (object) {
if (!object) {
return object;
}
for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {
var iterable = arguments[argsIndex];
if (iterable) {
for (var key in iterable) {
if (object[key] == null) {
object[key] = iterable[key];
}
}
}
}
return object;
}
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
var render;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n";
try {
render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
return _;
})({});
if (location.hostname === 'todomvc.com') {
window._gaq = [['_setAccount','UA-31081062-1'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'));
}
function redirect() {
if (location.hostname === 'tastejs.github.io') {
location.href = location.href.replace('tastejs.github.io/todomvc', 'todomvc.com');
}
}
function findRoot() {
var base;
[/labs/, /\w*-examples/].forEach(function (href) {
var match = location.href.match(href);
if (!base && match) {
base = location.href.indexOf(match);
}
});
return location.href.substr(0, base);
}
function getFile(file, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', findRoot() + file, true);
xhr.send();
xhr.onload = function () {
if (xhr.status === 200 && callback) {
callback(xhr.responseText);
}
};
}
function Learn(learnJSON, config) {
if (!(this instanceof Learn)) {
return new Learn(learnJSON, config);
}
var template, framework;
if (typeof learnJSON !== 'object') {
try {
learnJSON = JSON.parse(learnJSON);
} catch (e) {
return;
}
}
if (config) {
template = config.template;
framework = config.framework;
}
if (!template && learnJSON.templates) {
template = learnJSON.templates.todomvc;
}
if (!framework && document.querySelector('[data-framework]')) {
framework = document.querySelector('[data-framework]').getAttribute('data-framework');
}
if (template && learnJSON[framework]) {
this.frameworkJSON = learnJSON[framework];
this.template = template;
this.append();
}
}
Learn.prototype.append = function () {
var aside = document.createElement('aside');
aside.innerHTML = _.template(this.template, this.frameworkJSON);
aside.className = 'learn';
// Localize demo links
var demoLinks = aside.querySelectorAll('.demo-link');
Array.prototype.forEach.call(demoLinks, function (demoLink) {
demoLink.setAttribute('href', findRoot() + demoLink.getAttribute('href'));
});
document.body.className = (document.body.className + ' learn-bar').trim();
document.body.insertAdjacentHTML('afterBegin', aside.outerHTML);
};
redirect();
getFile('learn.json', Learn);
})();
{
"name": "todomvc-common",
"version": "0.1.7",
"gitHead": "42348a8146fe0be847b93cd98664813fbae62be9",
"_id": "todomvc-common@0.1.7",
"readme": "ERROR: No README.md file found!",
"description": "ERROR: No README.md file found!",
"repository": {
"type": "git",
"url": "git://github.com/tastejs/todomvc-common.git"
}
}
\ No newline at end of file
<!doctype html>
<html lang="en" ng-app="todomvc" data-framework="firebase">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Firebase &amp; AngularJS • TodoMVC</title>
<link rel="stylesheet" href="bower_components/todomvc-common/base.css">
<style>[ng-cloak] { display: none; }</style>
</head>
<body>
<section id="todoapp" ng-controller="TodoCtrl">
<header id="header">
<h1>todos</h1>
<form id="todo-form" ng-submit="addTodo()">
<input id="new-todo" placeholder="What needs to be done?" ng-model="newTodo" autofocus>
</form>
</header>
<section id="main" ng-show="todos" ng-cloak>
<input id="toggle-all" type="checkbox" ng-model="allChecked" ng-click="markAll(allChecked)">
<label for="toggle-all">Mark all as complete</label>
<ul id="todo-list">
<li ng-repeat="(id, todo) in todos | todoFilter" ng-class="{completed: todo.completed, editing: todo == editedTodo}">
<div class="view">
<input class="toggle" type="checkbox" ng-model="todo.completed">
<label ng-dblclick="editTodo(id)">{{todo.title}}</label>
<button class="destroy" ng-click="removeTodo(id)"></button>
</div>
<form ng-submit="doneEditing(id)">
<input class="edit" ng-model="todo.title" todo-escape="revertEditing(id)" todo-blur="doneEditing(id)" todo-focus="todo == editedTodo">
</form>
</li>
</ul>
</section>
<footer id="footer" ng-show="todos" ng-cloak>
<span id="todo-count"><strong>{{remainingCount}}</strong>
<ng-pluralize count="remainingCount" when="{ one: 'item left', other: 'items left' }"></ng-pluralize>
</span>
<ul id="filters">
<li>
<a ng-class="{selected: location.path() == '/'} " href="#/">All</a>
</li>
<li>
<a ng-class="{selected: location.path() == '/active'}" href="#/active">Active</a>
</li>
<li>
<a ng-class="{selected: location.path() == '/completed'}" href="#/completed">Completed</a>
</li>
</ul>
<button id="clear-completed" ng-click="clearCompletedTodos()" ng-show="completedCount">Clear completed ({{completedCount}})</button>
</footer>
</section>
<footer id="info">
<p>Double-click to edit a todo</p>
<p>Credits:
<a href="http://twitter.com/cburgdorf">Christoph Burgdorf</a>,
<a href="http://ericbidelman.com">Eric Bidelman</a>,
<a href="http://jacobmumm.com">Jacob Mumm</a> and
<a href="http://igorminar.com">Igor Minar</a>
</p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer>
<script src="https://cdn.firebase.com/v0/firebase.js"></script>
<script src="bower_components/todomvc-common/base.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-fire/angularFire.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/todoCtrl.js"></script>
<script src="js/directives/todoFocus.js"></script>
<script src="js/directives/todoBlur.js"></script>
<script src="js/directives/todoEscape.js"></script>
</body>
</html>
/*global angular */
/*jshint unused:false */
'use strict';
/**
* The main TodoMVC app module
*
* @type {angular.Module}
*/
var todomvc = angular.module('todomvc', ['firebase']);
todomvc.filter('todoFilter', function ($location) {
return function (input) {
var filtered = {};
angular.forEach(input, function (todo, id) {
var path = $location.path();
if (path === '/active') {
if (todo.completed === false) filtered[id] = todo;
} else if (path === '/completed') {
if (todo.completed === true) filtered[id] = todo;
} else {
filtered[id] = todo;
}
});
return filtered;
}
});
\ No newline at end of file
/*global todomvc, angular */
'use strict';
/**
* The main controller for the app. The controller:
* - retrieves and persists the model via the angularFire service
* - exposes the model to the template and provides event handlers
*/
todomvc.controller('TodoCtrl', function TodoCtrl($scope, $location, angularFire) {
var url = 'https://todomvc-angular.firebaseio.com/';
$scope.newTodo = '';
$scope.editedTodo = null;
if ($location.path() === '') {
$location.path('/');
}
$scope.location = $location;
angularFire(url, $scope, 'todos', {}).then(function() {
onDataLoaded($scope, $location, url);
});
});
function onDataLoaded($scope, $location, url) {
$scope.$watch('todos', function () {
var total = 0;
var remaining = 0;
angular.forEach($scope.todos, function(todo) {
total++;
if (todo.completed === false) remaining++;
});
$scope.remainingCount = remaining;
$scope.completedCount = total - remaining;
$scope.allChecked = !$scope.remainingCount;
}, true);
$scope.addTodo = function () {
var newTodo = $scope.newTodo.trim();
if (!newTodo.length) {
return;
}
$scope.todos[new Firebase(url).push().name()] = {
title: newTodo,
completed: false
};
$scope.newTodo = '';
};
$scope.editTodo = function (id) {
$scope.editedTodo = $scope.todos[id];
$scope.originalTodo = angular.extend({}, $scope.editedTodo);
};
$scope.doneEditing = function (id) {
$scope.editedTodo = null;
var title = $scope.todos[id].title.trim();
if (!title) {
$scope.removeTodo(id);
}
};
$scope.revertEditing = function (id) {
$scope.todos[id] = $scope.originalTodo;
$scope.doneEditing(id);
};
$scope.removeTodo = function (id) {
delete $scope.todos[id];
};
$scope.clearCompletedTodos = function () {
var notCompleted = {};
angular.forEach($scope.todos, function (todo, id) {
if (!todo.completed) notCompleted[id] = todo;
});
$scope.todos = notCompleted;
};
$scope.markAll = function (completed) {
angular.forEach($scope.todos, function (todo) {
todo.completed = completed;
});
};
}
\ No newline at end of file
/*global todomvc */
'use strict';
/**
* Directive that executes an expression when the element it is applied to loses focus
*/
todomvc.directive('todoBlur', function () {
return function (scope, elem, attrs) {
elem.bind('blur', function () {
scope.$apply(attrs.todoBlur);
});
};
});
/*global todomvc */
'use strict';
/**
* Directive that executes an expression when the element it is applied to gets
* an `escape` keydown event.
*/
todomvc.directive('todoBlur', function () {
var ESCAPE_KEY = 27;
return function (scope, elem, attrs) {
elem.bind('keydown', function (event) {
if (event.keyCode === ESCAPE_KEY) {
scope.$apply(attrs.todoEscape);
}
});
};
});
/*global todomvc */
'use strict';
/**
* Directive that places focus on the element it is applied to when the expression it binds to evaluates to true
*/
todomvc.directive('todoFocus', function todoFocus($timeout) {
return function (scope, elem, attrs) {
scope.$watch(attrs.todoFocus, function (newVal) {
if (newVal) {
$timeout(function () {
elem[0].focus();
}, 0, false);
}
});
};
});
# Firebase & AngularJS TodoMVC Example
> Firebase is a scalable realtime backend that lets you build apps fast without managing servers.
> _[Firebase - firebase.com](https://www.firebase.com)_
## Learning Firebase
The [Firebase website](https://www.firebase.com) is a great resource for getting started.
Here are some links you may find helpful:
* [Tutorial](https://www.firebase.com/tutorial/)
* [Documentation & Examples](https://www.firebase.com/docs/)
* [API Reference](https://www.firebase.com/docs/javascript/firebase/)
* [Blog](https://www.firebase.com/blog/)
* [Firebase on Github](http://firebase.github.io)
* [AngularJS bindings for Firebase](http://github.com/firebase/angularFire)
Get help from other AngularJS users:
* [Firebase on StackOverflow](http://stackoverflow.com/questions/tagged/firebase)
* [Google Groups mailing list](https://groups.google.com/forum/?fromgroups#!forum/firebase-talk)
* [Firebase on Twitter](https://twitter.com/Firebase)
* [Firebase on Facebook](https://facebook.com/Firebase)
* [Firebase on Google +](https://plus.google.com/115330003035930967645/posts)
_If you have other helpful links to share, or find any of the links above no longer work, please [let us know](https://github.com/tastejs/todomvc/issues)._
## Implementation
Firebase provides a realtime persistence layer for JSON data. In this example,
we combine Firebase with AngularJS to create a collaborative TODO app where
the TODO items are persisted and updated in realtime.
There is very little difference between this app and the vanilla AngularJS
TODO app in how AngularJS is used. The only significant difference is the
use of [AngularFire](http://github.com/firebase/angularFire), which provides
an AngularJS service for persisting and updating TODO items in realtime.
......@@ -860,6 +860,49 @@
}]
}]
},
"firebase": {
"name": "Firebase",
"description": "Firebase is a scalable realtime backend that lets you build apps fast without managing servers.",
"homepage": "firebase.com",
"examples": [{
"name": "Firebase + AngularJS Realtime Example",
"url": "labs/architecture-examples/firebase-angular"
}],
"link_groups": [{
"heading": "Official Resources",
"links": [{
"name": "Tutorial",
"url": "https://www.firebase.com/tutorial/"
}, {
"name": "Documentation & Examples",
"url": "https://www.firebase.com/docs/"
}, {
"name": "Blog",
"url": "https://www.firebase.com/blog/"
}, {
"name": "Firebase on GitHub",
"url": "http://firebase.github.io"
}]
}, {
"heading": "Community",
"links": [{
"name": "Firebase on StackOverflow",
"url": "http://stackoverflow.com/questions/tagged/firebase"
}, {
"name": "Mailing list on Google Groups",
"url": "https://groups.google.com/forum/?fromgroups#!forum/firebase-talk"
}, {
"name": "Firebase on Twitter",
"url": "http://twitter.com/Firebase"
}, {
"name": "Firebase on Facebook",
"url": "http://facebook.com/Firebase"
}, {
"name": "Firebase on Google +",
"url": "https://plus.google.com/115330003035930967645/posts"
}]
}]
},
"flight": {
"name": "Flight",
"description": "Flight is a lightweight, component-based JavaScript framework that maps behavior to DOM nodes.",
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment