July 26, 2012

Backbone: The framework that isn’t

Note

Presenter used a presentation tool that doesn’t have a back button. Ahem.

Synopsis

Backbone.js is often discussed alongside the many other popular client-side frameworks like Ember, Knockout, et cetera. This talk will discuss how Backbone.js is less like those opinionated frameworks and more like a set of glue libraries to build your own framework, and will also cover some useful patterns you can use in your own Backbone application.

Lots of hot client frameworks

  • Angular
  • Ember
  • Knockout
  • Spine
  • Backbone

Backbone is kind of opinionated

The fact that it leaves out even basic framework structure yet makes you make your own decisions

  • but you shouldn’t have to rewrite boilerplate
  • and you should still have a set of drop-in components that work well together
  • You should have the freedom to do what you want.

What do frameworks provide?

  • Models
  • Views
  • Controllers
  • Presenters
  • Observers
  • Routers

In other words, the glue you need to make something work.

What does backbone provide?

  • Models
var view - new SandwichView({model: rueben});
// view.model attribute set to reuben
  • Events instead of callbacks
this.collection.on('add', this.addItemView, this);

function(item){
    view.$('.js.item.container').append(
        (new SomeItemView({model:item})).render().el
    );
}
  • Ability to combine template context and user data
var BaseView = Backbone.View.extend({
    // snip giant chunk of code
});
  • Do the anti-pattern of having a fat router
app = Backbone.Router.Extend({
    // snip giant router function

});

Presenter’s opinions about Backbone

  • Provides Tight coupling between models and views that represent them.
  • 4 classes and a default sync sync method and kid of sets you loose with them
  • Doesn’t force you to follow a ‘Backbone Way’.
  • If your app isn’t trivial, Backbone might not be the right choice
  • If you need to handle lots of DOM and JS executions, Backbone might be a right choice.

Going Native: Practical scripting with the JavaScript Image Object

A Practical JavaScript talk

Note

This was an AWESOME talk. Great to see how digging into the fundamentals can allow you to do some really impressive things with a tiny bit of code.

Synopsis

JQuery, Dojo, Mootools, Ext, Prototype, Script.aculo.us, Backbone, Modernizer….[sigh]…it’s hard to keep up. Remember when there was just something called JavaScript? I do. Don’t get me wrong I love all the aforementioned libraries like a father loves his children, but when it is time to get practical and create performance solutions those babies got to go. I’m going to introduce you to an old friend of mine, the JavaScript native image object. This ol’boy is perhaps one of the most powerful objects in JavaScript and he’s uber simple to get to know. I’m going to show you some of his tricks and try to convince you that he belongs in your JavaScript solutions tool belt!

What can the Image object do?

  • Handle Image Data
  • Server Communication (pre AJAX)
  • Analytics
  • Page Performance

Basic Image Object

var foo = new Image();
foo.src = url;
if(foo.complete) return true
else return false

Image Events

foo.onerror=function(){}
// 404
foo.onsuccess=function(){}
// 200
foo.onabort=function(){}
// cient timeout

image_beacon.js

To see events fired by rollover, these send out business processes on rollovers. This way they can track people’s usage of the site. For example, which image are people perhaps ‘right-clicking’ on and other things not normally detectable.

var quirkyURL = 'http://url.xyz'
var backupURL = 'http://url2.xyz'

var ms = 500;
var totalms = 5000;
var tries = Math.ceil(totalms/ms);
var beacon = new Image();

// create a recursive function
var check = function(){
    if (beacon.complete == false){
        if (tries--){
            // keep on checking until we run out of tries
            setTimeout(function(){check()}, ms);
        }
        else {
            window.removeEvent('unload', quickSend);
            beacon.src = backup; // never went so we go to backup location
        }
    }
    else{
        window.removeEvent('unload', quickSend);
        //ahhhhhhhh don't leave. Need. Moar. Time......
    }

};

//failsafe
var quickSend = window.addEvent('unload', function(){
    tries = 0;
    check();
});

beacon.src=quirkyURL;
check();

image_lazyload.js

How to load things as the page is scrolled:

var img = new Image();

img.onload=function(){
    el.src = img.src;
};

img.onerror=function(){
    el.src = (config.fallback)? config.fallback: "about:blank";
};

img.src = (config.src) ? config.src : config.fallback;

The point of it all

  • Adding in Frameworks slows things down. If you have a huge amount of data going back and forward on the site, say images, then loading JavaScript frameworks will slow you down.
  • If you can figure out how to do it in Native JavaScript in 4 lines of code, that’s better than loading Mootools or JQuery.

JS To Rule Them All

Note

This guy is a super-talented front end developer. Incredibly good JavaScript and CSS guy.

synopsis

One of the more cringe-inducing terms for any JS developer is “web page”. We’ve now reached the point where any meaningful experience needs to be an application. It also needs to be thoughtfully crafted to work on phones and tablets all the while having the level of animation and polish users have come to expect from the technology they use regardless of platform.

Static pages with responsive layouts aren’t going to cut it in this new universe, so we’ll look at using only JavaScript to structure applications, create and style markup, and also be platform aware in order to present users with an interactive experience suited for each device.

This talk will be a general theory overview accompanied by plenty of examples and very brief code demonstrations. It will cover interesting points along the way such as best practices for smooth UI and animation, content management, SEO, and even how to use these exact techniques to create native mobile applications.

Current state of affairs

  • Desktop sites like http://nfl.com or http://techcrunch.com, smashing as much content as possible into big scrolling pages
  • Separate mobile sites that “feel jenky”, not smooth like mobile apps
  • iOS/Android/etc mobile app

What can we do about it?

Write apps that run everywhere!

But…

  • You may be familiar with the term, “write once run everywhere”
  • But this is different. Write multiple views and route end users to the appropriate view

How?

  • Use good code structure
  • Device identification tools
  • Write controllers that present the correct view for whichever device the application is being used on.
  • The models, and controllers (mostly) can stay consistent
  • Coding flexible layouts

Why do this?

  • Above all else, it improves the user experience. Don’t send users to mobile app download pages!
  • Just the idea of creating applications instead of “web pages” helps narrow the focus to engaging users with a meaningful experience.

Try to stick to using only JS for the view

  • In the past:

    • Write a ton of markup
    • Separate out pieces of HTML via Mustache et al
    • But this gets clunky on larger efforts
  • Going forward:

    • Create an element, style it, and then appending it to a parent
    • Easier to debug, much faster to debug, less files open
    • Problem: Can be a bit problematic using JQuery on mobile. Maybe use JQuery Mobile?
var $tst $("<div class="test" />");
$test.size(100, 100).setBG('image.png');
$test.css({top: 100, left: 100});
$parent.append($test);

Not just static pages

  • Bad animation can be distracting and in the way, good animation can be useful to invoke emotion and hierarchy.
  • Getting rid of “click, reload, repeat”
  • Using animation to bridge the gap between content presentation

It’s like butter

“making things look pretty on mobile devices”

  • Going back to detecting device capabilities

  • Use CSS3 transitions applied with JS is the best performance way

  • Use top/left for desktop, and translateX/translateY for mobile. Use device detection to automatically convert left/top.

  • Watch out for firefox. You can easily have flickering images.

  • User translate3d for iOS

  • Use canvas only where absolute necessary

    • Use the smallest rendering area possible
    • Keep your canvas small!

Content Management

  • Techniques to use WordPress or other traditional CMS with this type of JS application.
  • Serving and loading JSON data
  • Using models to store and make that data accessible within the application.

Warning

CMS are not ideal for this sort of API thing unless your app is supposed to be the front end for a CMS.

SEO

Note

in other words, be able to present the content in standard markup so Google can pick it up for Search.

Mobile Applications

  • Now you have Smooth animation and performance indistinguishable from a native app

  • Same code base can be made to accommodate different devices with good routing controls

  • Thoughts on PhoneGap vs. Titanium:

    • Titanium > PhoneGap
    • PhoneGap hijacks the click method and this causes issues

Questions

  • When is your library going to be released?

    • My previous company owns the rights. I’m doing something new and hope to release it soon.
  • Can you use Modernizr for device capability detection?

    • Yes
  • Do you use load different size images or do you resize them in the JS?

    • Always load different size images. Resizing is a performance sink.