Last active
December 18, 2015 23:29
-
-
Save gschorkopf/5861807 to your computer and use it in GitHub Desktop.
An less functional solution to JS tasker, with namespacing and object constructors. Could use some bits of refactoring. Big thanks to one Franklin Webber for being awesome.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// jQuery "on page load" | |
$(function(){ | |
// Focus on the main field | |
$('input#task_text').focus(); | |
// Object constructor for task list | |
var TaskList = function(element) { | |
// Assigning 'this.element' property from input (a selector). 'this.element' could be called anything. | |
this.element = $(element); | |
// $.proxy takes is a way to assign 'this' in a specific context (here, a function) | |
this.element.on('click', $.proxy(function(event) { | |
$(event.target).toggleClass('completed'); | |
this.updateList(); | |
}, this)); | |
}; | |
// Functional properties of each list | |
TaskList.prototype = { | |
tasks : function() { | |
return this.element.children(); | |
}, | |
incompleteTasks: function() { | |
return this.tasks().not('li.completed'); | |
}, | |
count : function() { | |
return this.incompleteTasks().size(); | |
}, | |
addListItem: function(text) { | |
var task_li = "<li>" + text + "</li>"; | |
this.element.append(task_li); | |
$('input#task_text').val(""); | |
this.updateList(); | |
}, | |
updateList : function() { | |
this.updateCounter(); | |
this.sortTasks(); | |
}, | |
updateCounter : function() { | |
$('span#task_counter').text(this.count()) | |
}, | |
sortTasks : function() { | |
var incompleted = this.incompleteTasks().detach(); | |
this.element.prepend(incompleted) | |
} | |
}; | |
// Assigning a TaskList, which takes the input of a selector | |
var taskList = new TaskList("#tasks ul"); | |
// Adds list item using object; prevents page scroll | |
$('form#add_task').on('submit', function(event){ | |
event.preventDefault(); | |
taskList.addListItem($('input#task_text').val()); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment