vue2/examples/todomvc/js/app.js

83 lines
2.3 KiB
JavaScript
Raw Normal View History

2013-08-10 18:52:14 +08:00
var storageKey = 'todos-seedjs',
storedData = JSON.parse(localStorage.getItem(storageKey))
2013-08-07 14:03:16 +08:00
Seed.controller('Todos', function (scope) {
// regular properties -----------------------------------------------------
2013-08-10 19:56:59 +08:00
scope.todos = Array.isArray(storedData) ? storedData : []
scope.filter = location.hash.slice(2) || 'all'
scope.remaining = scope.todos.reduce(function (n, todo) {
2013-08-10 19:56:59 +08:00
return n + (todo.completed ? 0 : 1)
2013-08-07 14:03:16 +08:00
}, 0)
// computed properties ----------------------------------------------------
scope.total = {get: function () {
return scope.todos.length
}}
2013-08-07 14:03:16 +08:00
scope.completed = {get: function () {
return scope.total - scope.remaining
}}
2013-08-07 14:03:16 +08:00
scope.itemLabel = {get: function () {
return scope.remaining > 1 ? 'items' : 'item'
}}
2013-08-07 14:03:16 +08:00
scope.allDone = {
get: function () {
return scope.remaining === 0
},
set: function (value) {
scope.todos.forEach(function (todo) {
2013-08-10 19:56:59 +08:00
todo.completed = value
})
scope.remaining = value ? 0 : scope.total
}
}
2013-08-07 14:03:16 +08:00
// event handlers ---------------------------------------------------------
scope.addTodo = function (e) {
2013-08-09 10:36:52 +08:00
if (e.el.value) {
2013-08-10 19:56:59 +08:00
scope.todos.unshift({ title: e.el.value, completed: false })
2013-08-07 14:03:16 +08:00
e.el.value = ''
2013-08-09 10:36:52 +08:00
scope.remaining++
2013-08-07 14:03:16 +08:00
}
}
scope.removeTodo = function (e) {
scope.todos.remove(e.scope)
2013-08-10 19:56:59 +08:00
scope.remaining -= e.scope.completed ? 0 : 1
2013-08-07 14:03:16 +08:00
}
scope.updateCount = function (e) {
2013-08-10 19:56:59 +08:00
scope.remaining += e.scope.completed ? -1 : 1
2013-08-07 14:03:16 +08:00
}
scope.edit = function (e) {
e.scope.editing = true
}
scope.stopEdit = function (e) {
e.scope.editing = false
}
scope.removeCompleted = function () {
2013-08-10 02:22:31 +08:00
if (scope.completed === 0) return
2013-08-07 14:03:16 +08:00
scope.todos = scope.todos.filter(function (todo) {
2013-08-10 19:56:59 +08:00
return !todo.completed
2013-08-07 14:03:16 +08:00
})
}
// listen for hash change
window.addEventListener('hashchange', function () {
scope.filter = location.hash.slice(2)
})
2013-08-10 19:56:59 +08:00
// persist data on leave
window.addEventListener('beforeunload', function () {
localStorage.setItem(storageKey, scope.$serialize('todos'))
})
2013-08-07 14:03:16 +08:00
})
2013-08-10 11:24:12 +08:00
Seed.bootstrap({ debug: true })