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!
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 = {};
}
}
// New
function foo(bar) {
// Assigns only when undefined
bar || (bar = {});
}
// Old
function foo(bar) {
// Assigns bar on every call
bar = bar || {};
}
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);
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
}
});
}
// New
foo && foo.bar()
// Old
if (foo) {
foo.bar();
}
function foo(element){
var $el = (element instanceof $) ? element : $(element);
}