RepoMan — The Reaping
Today, we’re going to talk about MVC and templating in JS.
So MVC means model, view and controller. The model is a representation of data that lives on some server, the view is what the user sees in the browser and the controller is what gets stuff to and from the model. That probably misses a lot of subtlety and is not very accurate, but we’ll move on.
In class, we are working with API’s. In a way, they are our model. Our functions are kind of like a controller, grabbing stuff from the API and serving it to our views, which are our HTML templates.
The idea is to use jQuery to make requests to an API, store the returned data as a promise object, load HTML files and then, when ready, do something with it.
We can also have JS request HTML in this manner and inject the returned JS data into this HTML.
This means we can write several “partials” (to borrow a term from RoR) and have JS assemble them while inject the JS into the parts of HTML that need updating. This allows us to write one piece of code that can be populated several times with different info, keeping us D.R.Y.
It’s interesting to assemble this in JS, because in RoR, it was always kind of hidden magically away from me. It helps me understand more clearly how we can use RoR as a server API that just serves up JSON representations of our data to our JS functions that then put it into the view. Doing it with JS allows us to be more asynchronous with our requests.
I will continue to update this post as I get further into things and will almost definitely be correcting my mistakes. :D
- $.get is a shorthand Ajax function equivalent to
$.ajax({url: url,
data: data,
success: success,
dataType: dataType
});
- jqXHR is like a jQuery version of an XHR object, but more versatile b/c JSONP and other cross-domain GET requests do not use XHR.
- jqXHR implements the Promise interface and gets all its methods and behaviors… not sure what this means. But I guess it means that $.get doesn’t return a true promise, but for most purposes, it’s fine to call it one?
- jqXHR is what is returned by $.get.
- jqXHR can use a method “then” which is a combination of .done() and .fail() functionality. Like .done(), it can execute a callback function when the jqXHR object is returned. This callback function can take 3 arguments (data, textStatus, jqXHR). This is what Matt was talking about when he wrote,
.then(function(data, successMessage, promise)
in the code.
- the then method also takes a second function, which I am guessing gives it the .fail()functionality:
function( jqXHR, textStatus, errorThrown ) {});- The data value of the jqXHR object is what we want in our functions that we learned about today.
- My head hurts.