And here we are again, just as I promised with more Backbone.js. In this post I’m going to lead you through using templates rather than inserting html directly into the DOM like I showed you in the last example.
First, we add the tagName which we’ll set as a div and that will be the container that our view will go into, but you can define it as a section tag or any other tag you wish. If it’s not specified it will be an empty div by default and will create this.el no matter what tag you choose.
Second, we’ll give our view a property called template:
Before we move on, let’s look in our render function within the View constructor and strip out this line of code:
Third, lets give the render function a couple of new properties.
Let’s create a variable holding the underscore.js template function that needs only one argument: this.template which refers to the template from our html page.
var greeting_template = .template(this.template);
Using the greeting_template variable we just defined, pass it into this.$el.html() which will render our view template from our model data once we also pass in a reference to our models attributes:
Fourth, after setting up our Views, is to go back to where we called the render function from the last tutorial and refactor some of our code.
Taking advantage of chaining, let’s change this:
Lastly, let’s go to our HTML and play around with the Underscore templates so our View can be inserted onto our page!
So inside the div we made during the last tutorial called #test, we add a script type text/template with an id #greeting-template and we are referencing the attribute title that’s defined in our model which I wrapped in an h2 tag.
So yay, that’s it! You can find the files on Git Hub, and this time I included the files for Backbone.js and Underscore.js within the lib folder.
I won’t go into too much detail about how an MVC framework is structured, nor will I tear apart bit by bit Backbone.js’s wonderments and utilities, but I will start you off with the basics on what Models and Views are and in a later tutorial I will introduce Collections, Routes, and how Models and Views talk to each other. If you want a heavier more detailed introduction than I suggest reading Addy Osmani’s early release of his Backbone.js Applications book on Git Hub for the nitty gritty details. My goal here is to really tear it down to the utmost basics in hopes that you won’t be overwhelmed by all that you can accomplish with Backbone.
Before we get started you’ll need to add both the Backbone.js and Underscore.js files which can be found on the Backbone.js page. Underscore.js (or Lo-Dash can be used) is the only dependency for running Backbone so go ahead and throw those in your HTML (remember to place the Underscore reference before the Backbone file) and let’s get started.
So let’s get started!
The easiest way to think about Models is it’s where you store and describe your data. Models represent the data in your app and give it structure and basic functionality needed to begin separating your data from the DOM. When you create your Model Class, you can set the defaults for that data which can be extended by creating a Model Instance where you customize the model for domain-specific actions.
First you need to create a Model Class. A couple of things to remember about creating Model Classes are the names need to be capitalized and they should be singular. The Model Class is where you set the defaults for your data and it acts as a base to extend your Models from when you create Model Instances.
In the case of the humble “Hello World” example, the first order of business is to create a basic default for the title - this is actually optional and can be left blank, but why not show how it works right?
So you can see that we’ve created a Model Class with a default title attribute of “default”. So original I know!
Now we can create an instance of the Model Class which needs to be a lowercase version of the models name. When you create an instance of a model it basically says here’s a unique version of the original model that is passed that model’s data attributes. In the new Model Instance these attributes can be changed and/or you can add more attributes that are unique to that instance.
In this example I didn’t add any other attributes, but changed the default title attribute to “Hello World”. However, you could add an id, a url, name, value, etc for the Model Instance, even if you didn’t specify those defaults when you created the Model Class.
Now we move on to create a View Class for our models. While Models are where the data is set and represented, the views handle how that data is organized and outputed such as defining the templates and the user interface of the data.
For our example, we will continue keeping it simple and only define the render function which will present the model data however we tell it to. Normally you would want to create an initialize function that listens for any changes or updates to the model and bind the render function to the model’s change event, but I will dig deeper into how that works in the future. And since I’m cutting all the corners here - instead of using a template library like Underscore.js, we’ll just throw into the DOM our “Hello World” by inserting it with the html method.
Pay special attention to the this.el selector. It’s important because each instance of the View Class is associated with a view element (.el) which represents the top level DOM element, and by default it’s a <div> however you can set it to any HTML tag you want such as an <article> or a <p> tag.
Now we can create a new View Instance which is basically the same as creating a new Model Instance. Here we pass in options including the model instance. This makes sure that the new instance of the view receives all of the attributes that were set in the model instance.
Finally, you call the render function and pass the View Instance into the html method, again making sure you refer to the top level element using .el
The only thing that you need to include in your markup is:
<div id=”test”></div> and the references to jquery, underscore, and backbone and you’re all set!
Here is the complete example:
Here are the tutorial files (excluding Backbone and Underscore) on GitHub:
So I’ve been slowly learning Python over the last few months - via http://learnpythonthehardway.org/ by Zed Shaw and through http://www.codecademy.com/. I’m already a front-end developer and have some small bits of knowledge on OOP, but what I’ve noticed is that when you are starting to learn any language, it helps to play around in it via something that interests you. Well, duh right? But it’s not that simple. Sometimes what you are interested in is way beyond the scope of basic tutorials and your knowledge base and you find yourself stuck doing the redundant grocery store list tutorials. But, I’ve learned that you can manipulate almost any tutorial to fit your interests - and Zed Shaw’s are perfect for that after you’ve done his basic exercises.
My interests and passions happen to be in surface geology and GIS. Well, it’s not like I’m going to begin learning Python by building an application for tracking and modeling natural disasters and how they contribute to groundwater contamination, but since doing math with Python is so easy - it can handle some basic surface geology equations quite nicely.
So for some of the beginning tutorials in Learning Python the Hard Way, I grabbed my old school binder and looked at some of my notes on calculating the velocity of water in a stream with the continuity equation.
This particular exercise doesn’t require any math - but I still tried to incorporate something I enjoyed, so for exercise 10, extra credit #3 I wrote:
cfs = “cubic feet per second”
gradient = “feet per mile”
continuity_equation = “Q = V * A”
print “The velocity of water depends on many factors includiing the gradient of the streambed, and discharge of the water”
print “Discharge means the amount of water in a stream and is measured in:\n %s” % cfs
print “The gradient is obviously refering to the slope (which is the elevation change over a horizontal distance) and is measured in:\n %s” % gradient
print “Usually the greater the slope, the greater the velocity”
print “The continuity equation: %s breaks down as follows:\n Q is the discharge in cubic feet per second(cfs), V is the velocity in ft/sec while A is a cross-sectional area of a stream channel in ft^2” % continuity_equation
This prints out:
The velocity of water depends on many factors includiing the gradient of the streambed, and discharge of the water
Discharge means the amount of water in a stream and is measured in:
cubic feet per second
The gradient is obviously refering to the slope (which is the elevation change over a horizontal distance) and is measured in:
feet per mile
Usually the greater the slope, the greater the velocity
The continuity equation: Q = V * A breaks down as follows:
Q is the discharge in cubic feet per second(cfs), V is the velocity in ft/sec while A is a cross-sectional area of a stream channel in ft^2
While this is for sure not groundbreaking code - it does show that you can turn something that might be boring into a double learning experience whether it’s surface geology you’re into, genetics, accounting or whatever.
So I recently tried creating gradients with CSS3 following the tutorial from the book: Stunning CSS3 by Zoe Mickley Gillenwater. While the tutorial and explanation is pretty good, it didn’t really explain how to get the right target hsla values to begin with. Luckily, a few months ago I had run across an article by Chris Coyier (shocker) about hsla which was a lot more digestible than the other explanations out there about what hsla is and what all those values inside the parenthesis accomplish. What was even better than the explanation was the handy dandy tool Colors by Matt Patenaude which Mr. Coyier added a link to in his article. I’ve been using it for months because it lets you copy a color from anywhere and spits out the color value in whatever format you want, including hsla. This allowed me to just copy and paste the starting and ending colors for my gradient and all I had to do was adjust the starting and ending values!
So for half the day I attempted to install SASS onto my Mac without pulling every last strand of my hair out. For those who haven’t heard, SASS/SCSS is an extension of CSS which I’ve been toying with learning because it has the ability to create variables and allows nesting of selectors and even has some functions. Even better though are the mixins (reusable chunks of code) This is super hella cool because when you want to reuse some code you don’t have to rewrite it over and over which is really why I wanted SCSS so bad. Also, SASS/SCSS allows selector inheritance which is different than what CSS3 already does a pretty good job of with the nth child selector in that instead of just targeting a specific elector that is the child of an element, the SASS selector inheritance lets you plugin another selectors styles just by adding the elements name! By the way, SCSS is an updated version of SASS which will still be supported, but it kind of sounds like they won’t be working on it anymore as they call SCSS “the primary syntax” now.
So obviously this is awesome, but why the heck didn’t anyone tell me the difficulties of using the Mac terminal? I admit that I’ve been spoiled with having super software such as Visual Studios 2008 (even though I barely know how to use it) and the free text editor Notepad++ and haven’t had to use the command line to do much except test some basic programs while trying to learn C++. However, in order to install SASS you have to not only go into the Mac terminal, but if you get an error message and don’t know what the hell you’re doing you are pretty much out of luck because there are very few forums on the subject (at least ones that I found). So, I thought I would share my pain and suffering along with a few tips if anyone wants to do this and runs into similar problems.
I started this process by watching a ThinkVitamin video but I immediately ran into an error that wasn’t addressed. This was the problem: now that Haml and SCSS (or SASS) are officially separate projects, the video was outdated so when I followed the instructions to write: sudo gem install haml it only installed haml and not sass also. So when it asks you to check for proper install: sass -v it brings up an annoying “command not found”. Plus, if you look at the Sass website it tells you to install by typing in: gem install sass but if you don’t change the default settings on your Mac to “superuser” than you don’t have the permissions to make changes without the sudo added to the beginning. I haven’t bothered with this yet, but I will because it was a pain in the neck to figure out what else needed a sudo in fornt of it! Here is an article about enabling the root account from Spy Hill Research. Another error that popped up was about the path and it said:
WARNING: Installing to ~/.gem since /Library/Ruby/Gems/1.8 and /usr/bin aren’t both writable. WARNING: You don’t have /Users/.gem/ruby/1.8/bin in your PATH, gem executables will not run. Successfully installed sass-3.1.7
fun, huh? Venture Web makes it sound easy by changing/updating your $Path by giving you a link to an article that made no sense to me but I’m sure to all those who have experience using the Terminal on a Mac it is easy. Luckily I didn’t have to do this once I installed Sass separately from Haml using the sudo in order to get past those pesky user permissions.
So after getting everything installed (I ended up installing haml, sass, and compass all with the sudo gem install …) I tried to use it with TextMate that I downloaded using their free 30 day trial, but I don’t know why it gets good reviews. If I wanted an ugly user-unfriendly interface I would be using my PC (which I still think is easier to develop but not design on). I tried to get the bundle from github for TextMate but couldn’t get it to work and after reading what I needed to do to add the bundle from TextMate I said screw it and downloaded a free text editor that had SASS suport built in . I choose RadRails from Aptana Studios which is freaking awesome because it is FREE and worked without any other downloads or directions. I did try Coda for a second because it has a really pretty interface, but then I didn’t bother with trying to add the bundle when I realized it was $99. Now I am the first person to throw money at a problem when it exists past a couple of hours, but since it didn’t have the bundle pre-installed I didn’t think it was worth $5 at that point.
So here sits my trials and tribulations using the Mac terminal and trying to download the SCSS extension…hopefully tomorrow will bring some success from learning how to write it cause I need those damn Mixins (you can even pass arguments to them!)
Until next time….SLK