CRUD: My New App, Check Yo Self

I have taken a bit of a break from the coding/learning thing as I suffer from a bit of depression every now and again, outside of the usual. It’s a woman’s thing, as they say.

So while I was a bit down and cantankerous I took a break to tweak a few of my sites and read some documentation. After the bout of depression subsided, I dove into SQL.

Create, Read, Update, Delete: CRUD

I asked around in the Code Newbie Slack and asked my buddy Alex if I could use localStorage to store the markdown documents.

Let me backtrack.

When I was designing the app, I got the idea of having the markdown documents collect on the side of the app, sort of like the design template I was using. I knew I’d need to store those documents and really didn’t want to dive into databases.

I thought about using localStorage. Alex told me that localStorage has a capacity limit. I really don’t know how many texts someone would store and come back to, and while text files are minuscule, I don’t want to risk it.

I could go the I Need a Resume route and use setSessionCookie which would require less overhead. But if the user clears their cookies, all their texts would be wiped out.

I still plan to use setSessionCookie but I am not sure how I am going to work it in with storing the texts in the database.

CRUD is a SQL thing. 1.

ORMs and JavaScript May Save Me, Big Time

While learning SQL at Treehouse, Andrew Chalkley, the teacher, explained ORMs, or Object Relational Mapping software that helps you interface with a database in different languages. For instance, ActiveRecord for Ruby and Hibernate for Java.I was having a hard time understanding how to store the texts the users input, store the texts, and retrieve the texts up until that point in the course. Everything we did in the course was hard coded and I definitely understood I could not do that. ORMs to the rescue. Searched for an ORM for JavaScript and there are many, either through npm or other means, there are plenty. Still researching. Since I am using Postgres on Heroku, it needs to play nice with it and I found one called sequelize.js that looks like it will do the trick:


var Sequelize = require('sequelize');
var sequelize = new Sequelize('database', 'username', 'password');

var User = sequelize.define('user', {
  username: Sequelize.STRING,
  birthday: Sequelize.DATE
});

sequelize.sync().then(function() {
  return User.create({
    username: 'janedoe',
    birthday: new Date(1980, 6, 20)
  });
}).then(function(jane) {
  console.log(jane.get({
    plain: true
  }));
});

This snippet seems quite easy to grasp and will make interfacing with Heroku’s Postgres addon even easier. 2.

Coding Again

I plan on scanning more docs and getting the HTML up and going. I felt overwhelmed with the amount of stuff I needed to code. This is one area that hinders me still: not breaking big projects up into little pieces. I decided I have been at this enough that I should actually take Russ’s 3 and break that shit down. I fired up Drafts app on my iPhone and wrote down every task I needed and wanted to complete. Then I shifted those over to OmniFocus and Taskpaper. There are more tasks to add but I feel a sense of relief knowing that the ideas are down, and that I should work on one small bit of code at a time.

Thoughts?

I never know how to end these things. Let me know what you’re hacking on in the comments. Or not. It’s all good. ????


  1. Create: INSERT INTO, Read:, SELECT * FROM, Update: UPDATE SET, and, Delete: DELETE FROM. So that’s why they call database apps that are simple CRUD apps, which I understand finally. 
  2. Check out sequelize.js 
  3. Code Newbie field general, 1000XP 

ES6 and Lambdas

I am taking the JavaScript ES6 course on Treehouse. I should have waited a bit, as I am still learning ES5. Eric Elliott made the case that newbies should be learning ES6 right now as it is the current standard. So I am diving in.

One of the things that has me excited are lambda functions. JavaScript calls them Arrow functions, but I like the traditional name better. So for this article, I will call them lambda functions.

Here is an example of a lambda function being used in ES6:

[javascript]
‘use strict’
var Person = function (data) {
for (var key in data) {
this[key] = data[key];
}
this.getKeys = () => {
return Object.keys(this);
}
}

var Alena = new Person({ name: ‘Alena’, role: ‘Teacher’ });

console.log(‘Alena\’s Keys:’, Alena.getKeys()); // ‘this’ refers to ‘Alena’

var getKeys = Alena.getKeys;

console.log(getKeys()); // ‘this’ refers to the node process
[/javascript]

Here in the is a Person constructor object with a function that takes the parameter data. On this constructor is a method called getKeys that returns the object’s keys using a lambda function.

Below that, a new Person object is instantiated and we log the keys for the Alena object to the console.

The lambda function binds the function to the object, no matter where it is called.

If we were to take a look at the code before the writing the lambda function, it would look like this:

[javascript]
‘use strict’
var Person = function (data) {
for (var key in data) {
this[key] = data[key];
}
this.getKeys = function () {
return Object.keys(this);
}
}

var Alena = new Person({ name: ‘Alena’, role: ‘Teacher’ });

console.log(‘Alena\’s Keys:’, Alena.getKeys()); // ‘this’ refers to ‘Alena’

var getKeys = Alena.getKeys;

console.log(getKeys()); // ‘this’ refers to the node process
[/javascript]

This code will throw an exception because we are calling the getKeys method outside of the Person constructor code block. This means it is out of scope.

More Lambdas

When code gets messy like this:

[javascript]
‘use strict’;

var Teacher = function (data) {
this.name = data.name;
this.greet = function (studentCnt) {
let promise = new Promise(function (resolve, reject) {
if (studentCnt === 0) {
reject(‘Zero students in class’);
} else {
resolve(Hello to ${studentCnt} of my favorite students!);
}
});
return promise;
}
}

var Classroom = function (data) {
this.subject = data.name;
this.teacher = data.teacher;
this.students = [];
this.addStudent = function (data) {
this.students.push(data);
this.greet();
}
this.greet = () => {
this.teacher.greet(this.students.length).then(
(function (classroom) {
return function (greeting) {
console.log(${classroom.teacher.name} says:, greeting);
}
})(this),
function (err) {
console.log(err);
})
}
}

var myTeacher = new Teacher({ name: ‘James’ });
var myClassroom = new Classroom({ name: ‘The Future of JavaScript’, teacher: myTeacher });

myClassroom.addStudent({ name: ‘Dave’ });
[/javascript]

it is a good idea to scrap the spaghetti code and write something with lambda or arrow functions, and use JavaScript Promises:

[javascript]
‘use strict’;

var Teacher = function (data) {
this.name = data.name;
this.greet = function (studentCnt) {
let promise = new Promise(function (resolve, reject) {
if (studentCnt === 0) {
reject(‘Zero students in class’);
} else {
resolve(Hello to ${studentCnt} of my favorite students!);
}
});
return promise;
}
}

var Classroom = function (data) {
this.subject = data.name;
this.teacher = data.teacher;
this.students = [];
this.addStudent = function (data) {
this.students.push(data);
this.greet();
}
this.greet = () => {
this.teacher.greet(this.students.length).then(
greeting => console.log(${this.teacher.name} says:, greeting);
err => console.log(err);
}
}

var myTeacher = new Teacher({ name: ‘James’ });
var myClassroom = new Classroom({ name: ‘The Future of JavaScript’, teacher: myTeacher });

myClassroom.addStudent({ name: ‘Dave’ });
[/javascript]

You use Promises asynchronously with callback functions, handing those functions off to another scope. You must be careful that the promise can access its original scope, or it will throw an exception.

Web Dev CS 0134

I really want to see what the web development course has in store for me this semester. I wonder if we will use ES6. I doubt it, but I am hopeful.

NaNoWriMo? How About NaCoWriMo?

\"NaCoWriMo\"

November, if you’re an internet savvy fiction writer, is NaNoWriMo, or National Novel Writing Month. As a writer in my previous life, I participated in NaNoWriMo several times. The objective is to write 50,000 words of a novel in one month. It’s insanity personified. I spent countless nights awake writing to get to 50,000 words and only ever “won” once. You win a certificate and some nice discounts from writing software people. The community is great as well.

Well, I want to propose a NaCoWriMo, National Code Writing Month, where new devs especially, write as much new code, or contribute to a few new open source projects, or work on their own projects, everyday, for the month of November. You could also do a tutorial everyday, like Treehouse or Free Code Camp. Should you have a finished project? Nah. Coding is harder than writing is, despite what writers say, and so you should have something if you are working on a new project. If you’re contributing to an open source project, contribute to at least two or three.

So how do I measure winning? In NaNoWriMo you won when you got to 50,000 words on December 1st at midnight. How I measure it will be if you have a working framework of a project, have your green commit blocks filled, have your Free Code Camp logs filled green, everyday for a month. What do you win? The satisfaction of knowing you accomplished something, small or large, contributed to something large or small, that pushed you further towards your goal of becoming a competent developer.

Maybe I’ll thow in something good to the first person to complete NaCoWriMo, like a book or Amazon Gift card (I don’t have a lot of money so you’re looking at $25 max) or an iTunes Gift Card for that dev app you were eyeing.

Good idea? Let me know in the comments.

Day 8: HTML Tables and The DOM

\"DOM

The DOM

So today was basically going over HTML tables. Easy. Then we went through MDN JavaScript Web API to learn about the DOM.

Went inside Chrome Dev Tools to look at what the

window.document

was.

So the window is the entire window opened in your browser. You can get information from the window, call methods on it and functions. Usually you don’t write

window.document

to access the document, (which is part of the DOM or Document Object Model).

The DOM is basically the HTML document, arranged in a tree, with nodes that you can manipulate with JavaScript and jQuery.

HTML Tables

Self-explanatory really. So you have a few

<table></table>

tags under which you can have this:

<table>

  <thead>

   <tbody>

   <tfoot>

     <tr>

      <td></td>

     </tr>

   </tbody>

  </tfoot>

 </thead>

</table>

\"wpid-Screenshot-2015-08-20.jpg\" \"wpid-Screenshot-2015-08-20-1.jpg\"

Day 7: Drawing App

\"Day_7\"

We used more HTML5 and JavaScript in this exercise. We had an HTML5

<canvas></canvas>

element which we have to use JavaScript interactivity to; we can’t use pure jQuery to make this app work so if JavaScript is disabled, the app won’t work.

We used new event handlers like

$canvas.mousedown(function(e) {
 lastEvent = e;
 mouseDown = true;
}).mousemove(function(e) {
}).mouseup(function() {
}).mouseleave(function() {
});

Obviously this code doesn’t work in its current state, but I digress. So drawing the line in the app consists of

.mousedown() .mousemove() .mouseup() .mouseleave()

so when you click initally, mousedown, move the mouse, mousemove, release the button on the mouse, mouseup, and when the mouse leaves the DOM element it was bound to, mouseleave, which won’t make an awkward line when the mouse comes back into the DOM element.

Learned new methods like

.siblings()

which will access the siblings in a child element and execute an event handler or another method.

We learned JavaScript specific ways to make the canvas interactive. The code looks like this:

$canvas.mousedown(function(e) {
 lastEvent = e;
 mouseDown = true;
}).mousemove(function(e) {
 if(mouseDown) {
 context.beginPath();
 context.moveTo(lastEvent.offsetX, lastEvent.offsetY);
 context.lineTo(e.offsetX, e.offsetY);
 context.strokeStyle = color;
 context.stroke();
 lastEvent = e;
 }
}).mouseup(function() {
 mouseDown = false;
}).mouseleave(function() {
 $canvas.mouseup
});
context.beginPath()

and such are the ways in which you can implement drawing interactivity to your app. The full thing is on CodePen or just work with it here:

[codepen_embed height=\”800\” theme_id=\”0\” slug_hash=\”bdPrvw\” default_tab=\”result\” user=\”twhite96\”]See the Pen <a href=\’http://codepen.io/twhite96/pen/bdPrvw/\’>bdPrvw</a> by Tiffany White (<a href=\’http://codepen.io/twhite96\’>@twhite96</a>) on <a href=\’http://codepen.io\’>CodePen</a>.[/codepen_embed]

Day 6: Password Forms & Tooltips

\"Day_6_badge\"

Here we just iterated on what we learned previously with:

.prop() .hide() .show() .val()

We learned two new methods,

.focus()

and

.keyup()

in relation to making it so the tooltips showed up when we clicked in the form’s password box, the tool tip being “password needs to be greater than 8 characters”. Once the 8 characters were put in, the tool tip disappeared.

The code looked something like this:

//Problem: Hints are shown even when form is valid
//Solution: Hide and show them at appropriate times
var $password = $("#password");
var $confirmPassword = $("#confirm_password");

//Hide hints
$("form span").hide();

function isPasswordValid() {
 return $password.val().length < 8;
}

function arePasswordsMatching() {
 return $password.val() === $confirmPassword.val();
}

function canSubmit() {
 return isPasswordValid() && arePasswordsMatching() && isUsernamePresent();
}

function passwordEvent(){
 //Find out if password is valid
 if(isPasswordValid()) {
 //Hide hint if valid
 $password.next().hide();
 } else {
 //else show hint
 $password.next().show();
 }
}

We practiced DRY programming by wrapping our resued methods, variables, etc in functions.

Day 5: Mobile Dropdown Menu

\"Day_5\"

We went over more of the same but learned some new methods and event handlers.

We learned about GET methods like

.prop()

which manipulates the DOM to get the property value of the first element in the set.

We learned about the

.change()

event handler with an anonymous function that we used to change the function of the dropdown menu. Before we had a Go button but what good is that? You would select the dropdown and the link to say, an FAQ, and then press \”Go\”. Well what about just going to that page when you touch or click on the dropdown menu link for that page? That is what we did by changing the whole behavior of the dropdown, and eliminating the appended Go button. Here is the code:

$select.change(function() {
 //Go to select\'s locaiton
 window.location = $select.val();
});

The

.val()

gets the select input without passing any arguments. Which is just clicking on a link that we specified in the HTML and the class we referenced in the jQuery that holds that link.

jQuery isn’t at all bad. And I have two more things to go to complete that part of the Front End Web Dev Track.

Day 4: Lightbox

\"Day_4\"

So yesterday we made a simple lightbox for a set of images, which I found hard to follow the lesson somehow.

Assigning jQuery elements to a variable has proven to be extremely useful. For instance this bit of code:

var $overlay = $(\'&lt;div id=&quot;overlay&quot;&gt;&lt;/div&gt;\');
var $image = $(&quot;&lt;img&gt;&quot;);
var $caption = $(&quot;&quot;);

$overlay.append($image);
// Add overly

$(&quot;body&quot;).append($overlay);
// An image
 // A caption
$overlay.append($caption);

We don\’t have to continually write out jQuery objects, we can just refer to them in the variables that preceded the block of code where we need them.

We did more appending and we learned about the

.attr()

method which we passed in the string, (\”href\”) after attaching it to

$(this)

. We wanted to make sure the image we clicked on in the image gallery would execute the behavior we wanted, which was popping up the lightbox. Using

$(this).attr(&quot;href&quot;)

assured us that we were clicking the linked image attribute in the HTML, and it wouldn\’t matter which image was clicked. Here is the last part of the code:

//Capture the click event on a link to an image
$(&quot;#imageGallery a&quot;).click(function(event){
   event.preventDefault();
   var imageLocation = $(this).attr(&quot;href&quot;);
 //Update overlay with the image linked in the link
   $image.attr(&quot;src&quot;, imageLocation);

//Show the overlay.
   $overlay.show();

//Get child\'s alt attribute and set caption
   var captionText = $(this).children(&quot;img&quot;).attr(&quot;alt&quot;);
   $caption.text(captionText);

});

//When overlay is clicked
  $overlay.click(function(){
 //Hide the overlay
  $overlay.hide();
});

Day 3: Event Handlers and Animations

\"Day_3_badge\"

I only did one jQuery class today as I had a lot to get done otherwise, but we went over documentation (which I never use the browser for because Dash) and preparing your prototype with comments, looking at your HTML file to see what you need to animate.

We went over manipulating the DOM (more on that in a moment) and Traversing the DOM and Event Handlers.

So you can manipulate the DOM with the [jquery].hide()[/jquery] method as well as the

.show()

. But we also added a button to the DOM in the HTML with this

$(".spoiler").append("<button>Reveal Spoiler!</button>");

Also we went over event handlers. So now that we have the button made in our HTML you can add a

$("button").click(function(){});

with passing an anonymous function in order to do something when the button we made is pressed.

$(this)

So in the code block with the button selector with the [jquery].click(function() {});[/jquery] you can do nifty things. So inside this code block we used

$(this).show();
$(this).remove();

I hadn’t really gotten my head around [jquery]$(this)[/jquery] until he explained that since we had two

<span>

elements under the

<div class= "spoiler"</div>


we needed to specify which button the

.show();

and

.remove();

when clicked. So I found that

$(this)

is magical. So when I click on the first spoiler button, this knows what to do with it. It knows I’m not clicking the second spoiler button. It knows to hide remove the second one when I am clicking the first. Cool stuff.

It was a pretty easy lesson since I have gone over this on Codecademy and Free Code Camp. But refresher is great for reinforcement.

Day 2: Rehashing jQuery Basics

\"jQuery_badge\"

So today I went over jQuery basics, documentation and a total disruption of what I learned on Free Code Camp and Codecademy.

At both Free Code Camp and Codecademy I learned to write:

$(document).ready

before all the other code to help load the DOM before the rest of the page gets loaded. Without that, the wisdom was, some of your code wouldn’t load first, animations, etc would break because they were loaded a little down further in your js document.

But throughout Treehouse courses we always put the script tags at the end of the HTML document, right before the end

<body>

tag. This loads the document first before any JavaScript or jQuery.

So imagine my surprise when we were writing:

$(“.warning”).hide().show(“slow”);

without the

$(document).ready

at the top of the document.

Basically it was all videos. I’ll post more tomorrow as I do it. Excited about my progress.