Skip to content

Instantly share code, notes, and snippets.

@joneath
Created June 25, 2012 22:42
Show Gist options
  • Save joneath/2991912 to your computer and use it in GitHub Desktop.
Save joneath/2991912 to your computer and use it in GitHub Desktop.
Backbone Source Learnings

Backbone Source Learnings

Models

#previousAttributes()

previousAttributes internally uses _.clone(). Previous attributes are only shallow copies so nested objects will be references. This means nested objects will show the current state of the object not the previous!

General

Undefined Assignment

Useful for when a function is called multiple times and an external property is set on the first call.

// New
function bar() {
	var foo = this.foo || (this.foo = {});
}

// Old
function bar() {
	var foo;
	if (this.foo) {
		foo = this.foo;
	} else {
		foo = this.foo = {};		
	}
}

Default Arguments

// New
function foo(bar) {
	// Assigns only when undefined
	bar || (bar = {});
}

// Old
function foo(bar) {
	// Assigns bar on every call
	bar = bar || {};
}

Extend Takes n Arguments

Extend takes as many arguments/objects as you pass it. It extends from right to left until one object remains.

var foo = _.extend({}, defaults, attrs);

Clone Options Argument

When passing an options argument to a function that will use it in a callback, make sure to clone the options. This is because arguments are passed by reference, so by the time your callback fires, the options could have changed externally.

function foo(options) {
	options = options ? _.clone(options) : {};
	
	$.ajax({
		url: "/foo"
	}).done(function(resp) {
		// is options.bar still options.bar?
		if (options.bar) {
			// Do something
		}
	});	
}

Run Dependent Code Using &&

// New
foo && foo.bar()

// Old
if (foo) {
	foo.bar();
}

Force jQuery Element

function foo(element){
	var $el = (element instanceof $) ? element : $(element);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment