home ~ previous

Backbone.js

Let’s be blunt. If you want to be a front end developer and stay employed, you have to know Backbone.js. One could argue for other MV* frameworks and I am sure their justifications are sound, but check the job adverts …. you just have to spend time with it.

Aside from its MV* (Backbone is not really MVC it’s MV...yawn ….- Google it, others will describe it far better than I), it does a rather neat job of extending objects (Backbone’s dependant on underscore.js, but I feel it seems to implement it a little better than underscore.js itself).

Extending objects

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Create an object and apply the Backbone.Model.extend to it.
// This  creates a series of defaults that can be extended by other objects

var Person = Backbone.Model.extend({
	defaults: {
		name: 'John Smith',
		age: 30,
		occupation: 'Developer',
		legs: 2,
		arms: 2,
		hair: "blond",
		sex: "male"
	},
	basedAt: function () {
		return this.get('name') + ' is based at the London office';
	}
});

// instantiate the object

person = new Person();

// Create a new object. Give the name a property value, mindful that all the default
// values of the person object have been extended

person2 = new Person({
	name: "Paul"
});

// Create another new object. Give the name a property value, mindful that all the default 
// values of the person object have been extended

person3 = new Person ({
	age: 24,
	bones: "yes"
});

// Output them to the console

console.log (person.get("name"));
console.log (person2.get("name"));
console.log (person3.get("bones"));

console.log (person.basedAt() + " and is " + person.get("sex") );

// We can also overwrite the value of an object

person.set ({
	name: "Panda"
});

console.log (person.get("name"));