It's a simple words counter app ..
$(document).ready(function() {
var wordsCounter = (function() {
function init() {
bindEvents();
}
// cache dom
var $textArea = $('#textArea');
var $words = $('#words'); //a span
var $chars = $('#chars'); //a span
function bindEvents() {
$textArea.on('keyup', updateTextArea);
}
// $textArea click callback function
function updateTextArea() {
var text = $textArea.val();
var numOfChars = text.length;
var numOfWords = countWords(text);
$chars.html(numOfChars);
$words.html(numOfWords);
}
// counts words for a given string
function countWords(str){
var cnt = 0;
var flag = true;
for(var i = 0; i < str.length; i++){
if(str[i] !== " " && flag){
flag = false;
cnt++;
}else if(str[i] === " "){
flag = true;
}
}
return cnt;
};
return {
init: init
}
}());
wordsCounter.init();
});
What are other good ways I can structure this code?
Also if i'm working on a larger project, should it all be in a one IIFE like this or should I divide into more than one IIFE everyone doing related things?
Aucun commentaire:
Enregistrer un commentaire