Commit d7f1a1f2 authored by Addy Osmani's avatar Addy Osmani

Merge pull request #33 from fredwu/master

Implemented a new SpineJS version using CoffeeScript with the latest SpineJS 1.0.5
parents ea52fa70 7d56ad3f
.DS_Store
jQuery(function($){
window.Tasks = Spine.Controller.create({
tag: "li",
proxied: ["render", "remove"],
events: {
"change input[type=checkbox]": "toggle",
"click .destroy": "destroy",
"dblclick .view": "edit",
"keypress input[type=text]": "blurOnEnter",
"blur input[type=text]": "close"
},
elements: {
"input[type=text]": "input",
".item": "wrapper"
},
init: function(){
this.item.bind("update", this.render);
this.item.bind("destroy", this.remove);
},
render: function(){
var elements = $("#taskTemplate").tmpl(this.item);
this.el.html(elements);
this.refreshElements();
return this;
},
toggle: function(){
this.item.done = !this.item.done;
this.item.save();
},
destroy: function(){
this.item.destroy();
},
edit: function(){
this.wrapper.addClass("editing");
this.input.focus();
},
blurOnEnter: function(e) {
if (e.keyCode == 13) e.target.blur();
},
close: function(){
this.wrapper.removeClass("editing");
this.item.updateAttributes({name: this.input.val()});
},
remove: function(){
this.el.remove();
}
});
window.TaskApp = Spine.Controller.create({
el: $("#tasks"),
proxied: ["addOne", "addAll", "renderCount"],
events: {
"submit form": "create",
"click .clear": "clear"
},
elements: {
".items": "items",
".countVal": "count",
".clear": "clear",
"form input": "input"
},
init: function(){
Task.bind("create", this.addOne);
Task.bind("refresh", this.addAll);
Task.bind("refresh change", this.renderCount);
Task.fetch();
},
addOne: function(task) {
var view = Tasks.init({item: task});
this.items.append(view.render().el);
},
addAll: function() {
Task.each(this.addOne);
},
create: function(){
Task.create({name: this.input.val()});
this.input.val("");
return false;
},
clear: function(){
Task.destroyDone();
},
renderCount: function(){
var active = Task.active().length;
this.count.text(active + ' left');
var inactive = Task.done().length;
this.clear[inactive ? "show" : "hide"]();
}
});
window.App = TaskApp.init();
});
\ No newline at end of file
// Create the Task model.
var Task = Spine.Model.setup("Task", ["name", "done"]);
// Persist model between page reloads.
Task.extend(Spine.Model.Local);
Task.extend({
// Return all active tasks.
active: function(){
return(this.select(function(item){ return !item.done; }));
},
// Return all done tasks.
done: function(){
return(this.select(function(item){ return !!item.done; }));
},
// Clear all done tasks.
destroyDone: function(){
jQuery(this.done()).each(function(i, rec){ rec.destroy(); });
}
});
\ No newline at end of file
......@@ -15,12 +15,12 @@ body {
width: 520px;
margin: 0 auto 40px auto;
background: white;
-moz-box-shadow: rgba(0, 0, 0, 0.2) 0 2px 6px 0;
-webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 2px 6px 0;
-o-box-shadow: rgba(0, 0, 0, 0.2) 0 2px 6px 0;
box-shadow: rgba(0, 0, 0, 0.2) 0 2px 6px 0;
-moz-border-radius: 0 0 5px 5px;
-o-border-radius: 0 0 5px 5px;
-webkit-border-radius: 0 0 5px 5px;
......@@ -47,7 +47,7 @@ body {
outline: none;
padding: 6px;
border: 1px solid #999999;
-moz-box-shadow: rgba(0, 0, 0, 0.2) 0 1px 2px 0 inset;
-webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 1px 2px 0 inset;
-o-box-shadow: rgba(0, 0, 0, 0.2) 0 1px 2px 0 inset;
......@@ -98,13 +98,13 @@ body {
display: block;
margin: 20px -20px -20px -20px;
overflow: hidden;
color: #555555;
background: #f4fce8;
border-top: 1px solid #ededed;
padding: 0 20px;
line-height: 36px;
-moz-border-radius: 0 0 5px 5px;
-o-border-radius: 0 0 5px 5px;
-webkit-border-radius: 0 0 5px 5px;
......@@ -116,24 +116,24 @@ body {
float: right;
line-height: 20px;
text-decoration: none;
background: rgba(0, 0, 0, 0.1);
color: #555555;
font-size: 11px;
margin-top: 8px;
margin-bottom:8px;
padding: 0 10px 1px;
-moz-border-radius: 12px;
-webkit-border-radius: 12px;
-o-border-radius: 12px;
border-radius: 12px;
-moz-box-shadow: rgba(0, 0, 0, 0.2) 0 -1px 0 0;
-webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 -1px 0 0;
-o-box-shadow: rgba(0, 0, 0, 0.2) 0 -1px 0 0;
box-shadow: rgba(0, 0, 0, 0.2) 0 -1px 0 0;
box-shadow: rgba(0, 0, 0, 0.2) 0 -1px 0 0;
cursor: pointer;
}
......@@ -152,4 +152,16 @@ body {
#tasks .count span {
font-weight: bold;
}
#credits {
width: 520px;
margin: 30px auto;
color: #999;
text-shadow: rgba(255, 255, 255, 0.8) 0 1px 0;
text-align: center;
}
#credits a {
color: #888;
}
\ No newline at end of file
......@@ -4,45 +4,48 @@
<title>Spine.js</title>
<link rel="stylesheet" href="css/application.css" type="text/css" charset="utf-8">
<script src="lib/json2.js" type="text/javascript" charset="utf-8"></script>
<script src="lib/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="lib/jquery.tmpl.js" type="text/javascript" charset="utf-8"></script>
<script src="lib/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="lib/jquery.tmpl.min.js" type="text/javascript" charset="utf-8"></script>
<script src="lib/spine.js" type="text/javascript" charset="utf-8"></script>
<script src="lib/spine.model.local.js" type="text/javascript" charset="utf-8"></script>
<script src="lib/local.js" type="text/javascript" charset="utf-8"></script>
<script src="app/models/task.js" type="text/javascript" charset="utf-8"></script>
<script src="app/application.js" type="text/javascript" charset="utf-8"></script>
<script type="text/x-jquery-tmpl" id="taskTemplate">
<div class="item {{if done}}done{{/if}}">
<div class="view" title="Double click to edit...">
<input type="checkbox" {{if done}}checked="checked"{{/if}}>
<span>${name}</span> <a class="destroy"></a>
</div>
<div class="edit">
<input type="text" value="${name}">
</div>
</div>
</script>
<script src="js/controllers/tasks.js" type="text/javascript" charset="utf-8"></script>
<script src="js/models/task.js" type="text/javascript" charset="utf-8"></script>
<script src="js/app.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="views">
<div id="tasks">
<h1>Todos</h1>
<form>
<input type="text" placeholder="What needs to be done?">
<form id="new-task">
<input name="name" type="text" placeholder="What needs to be done?">
</form>
<div class="items"></div>
<div class="items">
<script type="text/html" id="task-template">
<div class="item {{if done}}done{{/if}}">
<div class="view" title="Double click to edit...">
<input type="checkbox" {{if done}}checked="checked"{{/if}}>
<span>${name}</span> <a class="destroy"></a>
</div>
<form class="edit">
<input type="text" name="name" value="${name}">
</form>
</div>
</script>
</div>
<footer>
<a class="clear">Clear completed</a>
<div class="count"><span class="countVal"></span></div>
<div class="count"><span class="countVal"></span> left</div>
</footer>
</div>
</div>
<div id="credits">
Based on the official <a href="https://github.com/maccman/spine.todos">Spine.Todos</a>.
</div>
</body>
</html>
\ No newline at end of file
(function() {
var TaskApp;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
TaskApp = (function() {
__extends(TaskApp, Spine.Controller);
TaskApp.prototype.elements = {
'.items': 'tasks',
'.countVal': 'counter',
'a.clear': 'clearCompleted',
'form#new-task input[name=name]': 'newTaskName'
};
TaskApp.prototype.events = {
'submit form#new-task': 'new',
'click a.clear': 'clearCompleted'
};
function TaskApp() {
this.toggleClearCompleted = __bind(this.toggleClearCompleted, this);
this.renderCounter = __bind(this.renderCounter, this);
this.renderAll = __bind(this.renderAll, this);
this.renderNew = __bind(this.renderNew, this); TaskApp.__super__.constructor.apply(this, arguments);
Task.bind('create', this.renderNew);
Task.bind('refresh', this.renderAll);
Task.bind('refresh change', this.renderCounter);
Task.bind('refresh change', this.toggleClearCompleted);
Task.fetch();
}
TaskApp.prototype["new"] = function(e) {
e.preventDefault();
Task.fromForm('form#new-task').save();
return this.newTaskName.val('');
};
TaskApp.prototype.renderNew = function(task) {
var view;
view = new Tasks({
task: task
});
return this.tasks.append(view.render().el);
};
TaskApp.prototype.renderAll = function() {
return Task.each(this.renderNew);
};
TaskApp.prototype.renderCounter = function() {
return this.counter.text(Task.active().length);
};
TaskApp.prototype.toggleClearCompleted = function() {
if (Task.done().length) {
return this.clearCompleted.show();
} else {
return this.clearCompleted.hide();
}
};
TaskApp.prototype.clearCompleted = function() {
return Task.destroyDone();
};
return TaskApp;
})();
$(function() {
return new TaskApp({
el: $('#tasks')
});
});
}).call(this);
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
window.Tasks = (function() {
var ENTER_KEY, ESCAPE_KEY;
__extends(Tasks, Spine.Controller);
ENTER_KEY = 13;
ESCAPE_KEY = 27;
Tasks.prototype.elements = {
'form.edit': 'form'
};
Tasks.prototype.events = {
'click a.destroy': 'remove',
'click input[type=checkbox]': 'toggleStatus',
'dblclick .view': 'edit',
'keypress input[type=text]': 'finishEditOnEnter',
'blur input[type=text]': 'finishEdit'
};
function Tasks() {
this.render = __bind(this.render, this); Tasks.__super__.constructor.apply(this, arguments);
this.task.bind('update', this.render);
this.task.bind('destroy', this.release);
}
Tasks.prototype.render = function() {
this.replace($('#task-template').tmpl(this.task));
return this;
};
Tasks.prototype.remove = function() {
return this.task.destroy();
};
Tasks.prototype.toggleStatus = function() {
return this.task.updateAttribute('done', !this.task.done);
};
Tasks.prototype.edit = function() {
this.el.addClass('editing');
return this.$('input[name=name]').focus();
};
Tasks.prototype.finishEdit = function() {
this.el.removeClass('editing');
return this.task.fromForm(this.form).save();
};
Tasks.prototype.finishEditOnEnter = function(e) {
var _ref;
if ((_ref = e.keyCode) === ENTER_KEY || _ref === ESCAPE_KEY) {
return this.finishEdit();
}
};
return Tasks;
})();
}).call(this);
(function() {
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
window.Task = (function() {
__extends(Task, Spine.Model);
function Task() {
Task.__super__.constructor.apply(this, arguments);
}
Task.configure('Task', 'name', 'done');
Task.extend(Spine.Model.Local);
Task.prototype.validate = function() {
if (!$.trim(this.name)) return 'Task name is required';
};
Task.active = function() {
return this.select(function(task) {
return !task.done;
});
};
Task.done = function() {
return this.select(function(task) {
return !!task.done;
});
};
Task.destroyDone = function() {
var task, _i, _len, _ref, _results;
_ref = this.done();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
task = _ref[_i];
_results.push(task.destroy());
}
return _results;
};
return Task;
})();
}).call(this);
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/*
* jQuery Templates Plugin 1.0.0pre
* http://github.com/jquery/jquery-tmpl
* Requires jQuery 1.4.2
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function(a){var r=a.fn.domManip,d="_tmplitem",q=/^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,b={},f={},e,p={key:0,data:{}},i=0,c=0,l=[];function g(g,d,h,e){var c={data:e||(e===0||e===false)?e:d?d.data:{},_wrap:d?d._wrap:null,tmpl:null,parent:d||null,nodes:[],calls:u,nest:w,wrap:x,html:v,update:t};g&&a.extend(c,g,{nodes:[],parent:d});if(h){c.tmpl=h;c._ctnt=c._ctnt||c.tmpl(a,c);c.key=++i;(l.length?f:b)[i]=c}return c}a.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(f,d){a.fn[f]=function(n){var g=[],i=a(n),k,h,m,l,j=this.length===1&&this[0].parentNode;e=b||{};if(j&&j.nodeType===11&&j.childNodes.length===1&&i.length===1){i[d](this[0]);g=this}else{for(h=0,m=i.length;h<m;h++){c=h;k=(h>0?this.clone(true):this).get();a(i[h])[d](k);g=g.concat(k)}c=0;g=this.pushStack(g,f,i.selector)}l=e;e=null;a.tmpl.complete(l);return g}});a.fn.extend({tmpl:function(d,c,b){return a.tmpl(this[0],d,c,b)},tmplItem:function(){return a.tmplItem(this[0])},template:function(b){return a.template(b,this[0])},domManip:function(d,m,k){if(d[0]&&a.isArray(d[0])){var g=a.makeArray(arguments),h=d[0],j=h.length,i=0,f;while(i<j&&!(f=a.data(h[i++],"tmplItem")));if(f&&c)g[2]=function(b){a.tmpl.afterManip(this,b,k)};r.apply(this,g)}else r.apply(this,arguments);c=0;!e&&a.tmpl.complete(b);return this}});a.extend({tmpl:function(d,h,e,c){var i,k=!c;if(k){c=p;d=a.template[d]||a.template(null,d);f={}}else if(!d){d=c.tmpl;b[c.key]=c;c.nodes=[];c.wrapped&&n(c,c.wrapped);return a(j(c,null,c.tmpl(a,c)))}if(!d)return[];if(typeof h==="function")h=h.call(c||{});e&&e.wrapped&&n(e,e.wrapped);i=a.isArray(h)?a.map(h,function(a){return a?g(e,c,d,a):null}):[g(e,c,d,h)];return k?a(j(c,null,i)):i},tmplItem:function(b){var c;if(b instanceof a)b=b[0];while(b&&b.nodeType===1&&!(c=a.data(b,"tmplItem"))&&(b=b.parentNode));return c||p},template:function(c,b){if(b){if(typeof b==="string")b=o(b);else if(b instanceof a)b=b[0]||{};if(b.nodeType)b=a.data(b,"tmpl")||a.data(b,"tmpl",o(b.innerHTML));return typeof c==="string"?(a.template[c]=b):b}return c?typeof c!=="string"?a.template(null,c):a.template[c]||a.template(null,q.test(c)?c:a(c)):null},encode:function(a){return(""+a).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;")}});a.extend(a.tmpl,{tag:{tmpl:{_default:{$2:"null"},open:"if($notnull_1){__=__.concat($item.nest($1,$2));}"},wrap:{_default:{$2:"null"},open:"$item.calls(__,$1,$2);__=[];",close:"call=$item.calls();__=call._.concat($item.wrap(call,__));"},each:{_default:{$2:"$index, $value"},open:"if($notnull_1){$.each($1a,function($2){with(this){",close:"}});}"},"if":{open:"if(($notnull_1) && $1a){",close:"}"},"else":{_default:{$1:"true"},open:"}else if(($notnull_1) && $1a){"},html:{open:"if($notnull_1){__.push($1a);}"},"=":{_default:{$1:"$data"},open:"if($notnull_1){__.push($.encode($1a));}"},"!":{open:""}},complete:function(){b={}},afterManip:function(f,b,d){var e=b.nodeType===11?a.makeArray(b.childNodes):b.nodeType===1?[b]:[];d.call(f,b);m(e);c++}});function j(e,g,f){var b,c=f?a.map(f,function(a){return typeof a==="string"?e.key?a.replace(/(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g,"$1 "+d+'="'+e.key+'" $2'):a:j(a,e,a._ctnt)}):e;if(g)return c;c=c.join("");c.replace(/^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/,function(f,c,e,d){b=a(e).get();m(b);if(c)b=k(c).concat(b);if(d)b=b.concat(k(d))});return b?b:k(c)}function k(c){var b=document.createElement("div");b.innerHTML=c;return a.makeArray(b.childNodes)}function o(b){return new Function("jQuery","$item","var $=jQuery,call,__=[],$data=$item.data;with($data){__.push('"+a.trim(b).replace(/([\\'])/g,"\\$1").replace(/[\r\t\n]/g," ").replace(/\$\{([^\}]*)\}/g,"{{= $1}}").replace(/\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,function(m,l,k,g,b,c,d){var j=a.tmpl.tag[k],i,e,f;if(!j)throw"Unknown template tag: "+k;i=j._default||[];if(c&&!/\w$/.test(b)){b+=c;c=""}if(b){b=h(b);d=d?","+h(d)+")":c?")":"";e=c?b.indexOf(".")>-1?b+h(c):"("+b+").call($item"+d:b;f=c?e:"(typeof("+b+")==='function'?("+b+").call($item):("+b+"))"}else f=e=i.$1||"null";g=h(g);return"');"+j[l?"close":"open"].split("$notnull_1").join(b?"typeof("+b+")!=='undefined' && ("+b+")!=null":"true").split("$1a").join(f).split("$1").join(e).split("$2").join(g||i.$2||"")+"__.push('"})+"');}return __;")}function n(c,b){c._wrap=j(c,true,a.isArray(b)?b:[q.test(b)?b:a(b).html()]).join("")}function h(a){return a?a.replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}function s(b){var a=document.createElement("div");a.appendChild(b.cloneNode(true));return a.innerHTML}function m(o){var n="_"+c,k,j,l={},e,p,h;for(e=0,p=o.length;e<p;e++){if((k=o[e]).nodeType!==1)continue;j=k.getElementsByTagName("*");for(h=j.length-1;h>=0;h--)m(j[h]);m(k)}function m(j){var p,h=j,k,e,m;if(m=j.getAttribute(d)){while(h.parentNode&&(h=h.parentNode).nodeType===1&&!(p=h.getAttribute(d)));if(p!==m){h=h.parentNode?h.nodeType===11?0:h.getAttribute(d)||0:0;if(!(e=b[m])){e=f[m];e=g(e,b[h]||f[h]);e.key=++i;b[i]=e}c&&o(m)}j.removeAttribute(d)}else if(c&&(e=a.data(j,"tmplItem"))){o(e.key);b[e.key]=e;h=a.data(j.parentNode,"tmplItem");h=h?h.key:0}if(e){k=e;while(k&&k.key!=h){k.nodes.push(j);k=k.parent}delete e._ctnt;delete e._wrap;a.data(j,"tmplItem",e)}function o(a){a=a+n;e=l[a]=l[a]||g(e,b[e.parent.key+n]||e.parent)}}}function u(a,d,c,b){if(!a)return l.pop();l.push({_:a,tmpl:d,item:this,data:c,options:b})}function w(d,c,b){return a.tmpl(a.template(d),c,b,this)}function x(b,d){var c=b.options||{};c.wrapped=d;return a.tmpl(a.template(b.tmpl),b.data,c,b.item)}function v(d,c){var b=this._wrap;return a.map(a(a.isArray(b)?b.join(""):b).filter(d||"*"),function(a){return c?a.innerText||a.textContent:a.outerHTML||s(a)})}function t(){var b=this.nodes;a.tmpl(null,null,null,this).insertBefore(b[0]);a(b).remove()}})(jQuery);
\ No newline at end of file
This diff is collapsed.
(function() {
if (typeof Spine === "undefined" || Spine === null) {
Spine = require('spine');
}
Spine.Model.Local = {
extended: function() {
this.change(this.saveLocal);
return this.fetch(this.loadLocal);
},
saveLocal: function() {
var result;
result = JSON.stringify(this);
return localStorage[this.className] = result;
},
loadLocal: function() {
var result;
result = localStorage[this.className];
return this.refresh(result || [], {
clear: true
});
}
};
if (typeof module !== "undefined" && module !== null) {
module.exports = Spine.Model.Local;
}
}).call(this);
This diff is collapsed.
(function(Spine, $){
var Model = Spine.Model;
var getUrl = function(object){
if (!(object && object.url)) return null;
return((typeof object.url == "function") ? object.url() : object.url);
};
var methodMap = {
"create": "POST",
"update": "PUT",
"destroy": "DELETE",
"read": "GET"
};
var urlError = function() {
throw new Error("A 'url' property or function must be specified");
};
var ajaxSync = function(method, record){
if (Model._noSync) return;
var params = {
type: methodMap[method],
contentType: "application/json",
dataType: "json",
processData: false
};
if (method == "create" && record.model)
params.url = getUrl(record.parent);
else
params.url = getUrl(record);
if (!params.url) throw("Invalid URL");
if (method == "create" || method == "update") {
var data = {};
if (Model.ajaxPrefix) {
var prefix = record.parent.name.toLowerCase();
data[prefix] = record;
} else {
data = record;
}
params.data = JSON.stringify(data);
}
if (method == "read")
params.success = function(data){
(record.refresh || record.load).call(record, data);
};
params.error = function(xhr, s, e){
record.trigger("ajaxError", xhr, s, e);
};
$.ajax(params);
};
Model.Ajax = {
extended: function(){
this.sync(ajaxSync);
this.fetch(this.proxy(function(){
ajaxSync("read", this);
}));
}
};
Model.extend({
ajaxPrefix: false,
url: function() {
return "/" + this.name.toLowerCase() + "s"
},
noSync: function(callback){
Model._noSync = true;
callback.apply(callback, arguments);
Model._noSync = false;
}
});
Model.include({
url: function(){
var base = getUrl(this.parent);
base += (base.charAt(base.length - 1) == "/" ? "" : "/");
base += encodeURIComponent(this.id);
return base;
}
});
})(Spine, Spine.$);
\ No newline at end of file
Spine.Model.Local = {
extended: function(){
this.sync(this.proxy(this.saveLocal));
this.fetch(this.proxy(this.loadLocal));
},
saveLocal: function(){
var result = JSON.stringify(this);
localStorage[this.name] = result;
},
loadLocal: function(){
var result = localStorage[this.name];
if ( !result ) return;
var result = JSON.parse(result);
this.refresh(result);
}
};
\ No newline at end of file
class TaskApp extends Spine.Controller
elements:
'.items': 'tasks'
'.countVal': 'counter'
'a.clear': 'clearCompleted'
'form#new-task input[name=name]': 'newTaskName'
events:
'submit form#new-task': 'new'
'click a.clear': 'clearCompleted'
constructor: ->
super
Task.bind 'create', @renderNew
Task.bind 'refresh', @renderAll
Task.bind 'refresh change', @renderCounter
Task.bind 'refresh change', @toggleClearCompleted
Task.fetch()
new: (e) ->
e.preventDefault()
Task.fromForm('form#new-task').save()
@newTaskName.val('')
renderNew: (task) =>
view = new Tasks(task: task)
@tasks.append view.render().el
renderAll: =>
Task.each @renderNew
renderCounter: =>
@counter.text Task.active().length
toggleClearCompleted: =>
if Task.done().length
@clearCompleted.show()
else
@clearCompleted.hide()
clearCompleted: ->
Task.destroyDone()
$ ->
new TaskApp(el: $('#tasks'))
class window.Tasks extends Spine.Controller
ENTER_KEY = 13
ESCAPE_KEY = 27
elements:
'form.edit': 'form'
events:
'click a.destroy': 'remove'
'click input[type=checkbox]': 'toggleStatus'
'dblclick .view': 'edit'
'keypress input[type=text]': 'finishEditOnEnter'
'blur input[type=text]': 'finishEdit'
constructor: ->
super
@task.bind 'update', @render
@task.bind 'destroy', @release
render: =>
@replace $('#task-template').tmpl(@task)
this
remove: ->
@task.destroy()
toggleStatus: ->
@task.updateAttribute 'done', !@task.done
edit: ->
@el.addClass('editing')
@$('input[name=name]').focus()
finishEdit: ->
@el.removeClass('editing')
@task.fromForm(@form).save()
finishEditOnEnter: (e) ->
if e.keyCode in [ENTER_KEY, ESCAPE_KEY] then @finishEdit()
class window.Task extends Spine.Model
@configure 'Task', 'name', 'done'
@extend Spine.Model.Local
validate: ->
'Task name is required' unless $.trim(@name)
@active: ->
@select (task) -> !task.done
@done: ->
@select (task) -> !!task.done
@destroyDone: ->
task.destroy() for task in @done()
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