backbone.js Flashcards Preview

Web Technologies > backbone.js > Flashcards

Flashcards in backbone.js Deck (87)
Loading flashcards...
1
Q

Backbone Views are more like…

A

Controllers in traditional MVC

2
Q

What is a SPA?

A

Single Page Application

3
Q

What are routers responsible for?

A

Used in SPA’s - it responds to changes in the URL to update the page.

4
Q

What is a model?

A

Container for application data

5
Q

Modernizr.js is required to be where in the main HTML file?

A

The header. (I presume some dependency issues).

6
Q

Models contain the….

A

data and logic

7
Q

How do you declare a Model?

A

var Song = Backbone.Model.extend({ // config object });

8
Q

What does the initialize member of the config object in the model do?

A

Calls a method that initializes the object - a bit like a constructor.

9
Q

How do you inspect an object in the chrome console?

A

Just type its name at the prompt.

10
Q

How do models store attributes?

A

In a hash

11
Q

How do you add an attribute?

A

Call the set method (or pass a JSON object to the constructor).

12
Q

How do you get an attribute?

A

Call the ‘get’ method on the model, passing the name of the attribute.

13
Q

How do you delete an attribute?

A

Call the ‘unset’ method on model, passing the name of the attribute.

14
Q

How do you remove all attributes of a model at once?

A

Call the ‘clear’ method on the model.

15
Q

How can I query a model whether it has an attribute?

A

use the ‘has’ method on the model object.

16
Q

How would I set defaults on a model?

A

When creating the model, set the field ‘defaults’ with a json object containing the default objects.

var Song = Backbone.Model.extend({
    defaults: { 
        superman: "yes",
        superwoman: "no"
    }
});
17
Q

How do we implement Model validation?

A

Add a ‘validate’ function to the Model upon creation.

var Song = Backbone.Model.extend({
   validate: function(attrs) {
       if (!attrs.title) {
           return "Title is required.";
       }
   }
});

The validate function is run over the attributes when they are set.

18
Q

What does Backbone expect the return value of the validate function to be?

A

It should return a string explaining the error.

19
Q

How do we determine if a model is valid (assuming we’ve done some validation)?

A

call the isValid method on the object.

song.isValid();

20
Q

If the model is not valid - how can we determine what the error is?

A

The attribute (not method!) of the model object can be checked to see what the error messages are.

song.validationError

21
Q

How do you perform inheritance using Backbone?

A
Once you have an object - you call 'extend()' on it to create a new constructor function.
var Animal = Backbone.Model.extend({
    walk: function() { console.log("Animal walking..."); }
});
var Dog = Animal.extend();
var dog = new Dog();
dog.walk();
22
Q

How would you override a function in a model?

A
var Animal = Backbone.Model.extend({
    walk: function() {
        console.log("Animal walking...");
    }
});
var Dog = Animal.extend({
    walk: function() {
        console.log("Dog walking...");
    }
});
23
Q

How would you call the parent function of a method?

A
var Dog = Animal.extend({
   walk: function() {
       Animal.prototype.walk.apply(this);
   console.log("Dog walking...");    } });
24
Q

How does backbones model method map to HTTP verbs?

A

fetch() - GET
save() - PUT / POST
destroy() - DELETE

25
Q

How do you define the end point for a Backbone model?

A

The urlRoot attribute of a model defines the API endpoint.

var Song = Backbone.Model.extend({
    urlRoot: "/api/foobar/",
});
26
Q

If we setup a fetch like this - what does the HTTP request look like (given urlRoot is “/api/songs” ) ?

var song = new Song({ id: 1 });
song.fetch();
A

GET /api/songs/1

27
Q

Given the following statements, what does the HTTP request look like for this set of commands (assuming urlRoot of “/api/songs”)?

var song = new Song({ id: 1 });
song.fetch();
....
song.set("title", "Super fuck");
song.save();
A

PUT /api/songs/1

… HTTP body will contain data.

28
Q

Given the following statements, what does the HTTP request look like for this set of commands (assuming urlRoot of “/api/songs”)?

var song = new Song();

song. set(“title”, “Title”);
song. save();

A

POST /api/songs/1

…HTTP body will contain the data.

29
Q

Given the following statements, what does the HTTP request look like for this set of commands (assuming urlRoot of “/api/songs”)?

var song = new Song({ id: 1 });
song.delete();
A

DELETE /api/songs/1

30
Q

What do you do if your database doesn’t use the attribute id to identify the object that you are loading?

A

You can set the actual attribute using the idAttribute field on the object.

var Song  = new Backbone.Model.extend({
   idAttribute: "songId"
});

var song = new Song({ songId: 1 });

31
Q

Are the fetch / save/ delete methods synchronous or asynchronous?

A

Asynchronous.

32
Q

What callbacks do the fetch and destroy methods accept?

A

success
error

var song = new Song();
song.fetch({
   success: function() {},
   error: function() {}
});
33
Q

What is the difference between the way the success/error callbacks work with fetch / delete and save?

A

In save the callbacks are wrapped in an object that is the SECOND argument to the method.

var song = new Song();
song.save({.....}, {
   success: function() {},
   error: function() {}
});

The first argument is a hash of the attributes you would like to change.

34
Q

If you have done the following - how do you call the save method with success / error callbacks?

var song = new Song();
song.set("title", "Title");
A

song.save({}, {
success: function() {},
error: function() {}
});

// NOTE that the first field must be supplied, even if it is empty!!!!

35
Q

How do you create a collection of Song models?

A

var Songs = Backbone.Collection.extend();

36
Q

How do you add Song models to a collection?

A

two ways -

var songs = new Songs([ new Song({ title: “song 1” ]);

or

songs.add(new Song({ title: “Song 4” });

37
Q

What is significant about the models ‘add’ method?

A

It is not a backbone method - it is an underscore method and is available on all model types.

38
Q

The length property on the collection refers to what?

A

The number of models in the collection.

39
Q

The models are stored where in the collection?

A

The models property

40
Q

How do we usually retrieve models from a collection?

A

Using the at or get method of the collection.

41
Q

There are two id’s given to a backbone model, what are they?

A

The permanent, internal id given by the server. And the Client ID - or CID - which is a temporary id used to track the object on the client.

42
Q

How do you remove a model?

A

Use the Model.remove() method. It expects an object as a parameter - so you can use at or get to get the object, and then pass it to remove.

43
Q

The add method by default adds a model to the collection where?

A

At the end of the collection.

44
Q

How would you use the add method to insert a model in a specific index?

A

songs.add(myModel, { at: 0 });

NOTE: It’s not just an index - you have to pass a JSON object

45
Q

What other method can you use to add a model to a collection, other than add?

A

songs.push(myModel);

46
Q

What methods can you use to search a collection?

A

myCollection.where({ });
myCollection.findWhere({ });

NOTE: The methods take a hash containing the search key (i.e. a variable and it’s value)

47
Q

What is the difference between where and findware?

A

where will return an array, findWhere will return the first instance found, and only the first instance.

48
Q

How can you add multiple search clauses in the where method?

A

songs.where({ genre: “Jazz”, title: “Song 2” });

49
Q

What type of searches can ‘where’ be used for?

A

Essentially only string matches - to do more complicated searches you need to use the filter method.q

50
Q

How do you use the filter method to select items in a collection?

A

songs.filter(function(song) {
return song.get(“downloads”) > 100;
});

NOTE: This requires a predicate - this will be run on every model in the collection.

51
Q

What collection method could you use to iterate over the entire collection?

A

songs.each(function(song) {
console.log(song.get(“title”));
});

52
Q

To get data from the server, you use the fetch method. What hash can you use to send additional data to be used in the fetch?

A

data: {
page: 2,
otherstuff: “woot”
}

53
Q

What would the get request look like for the following:

var Songs = Backbone.Collection.extend({
   model: Song,
   url: "/api/songs"
});
var songs = new Songs();
songs.fetch({
   data: { page: 2 },
   success: function() {},
   error: function() {}
});
A

GET /api/songs?page=2

54
Q

The view is responsible for…

A

Rendering the content

Responding to changes in the model and DOM events

55
Q

What method is required in a Backbone View to draw the screen?

A

Render

56
Q

By convention, what do we return at the end of a render method?

A

this

57
Q

How do we create a Backbone view?

A

var SongView = Backbone.View.extend({ // Initialise stuff here });

58
Q

How do we refer to the views DOM element?

A

this.$el

59
Q

How do we specify what the DOM element is that should be rendered to by the render method (referenced by $el) ?

A

When creating the instance of the view.

var songView({ el: “#container” });

Note - we are passing a jQuery selector string to identify the DOM element.

60
Q

When you examine a Backbone view instance, you will notice that it has both a $el and an el attribute. What is the difference?

A

The $el is a case jQuery object - it is faster to use this when accessing the DOM element or any of its children, as opposed to building up your own jQuery query.

el is simply the raw jQuery selector string.

61
Q

If you don’t specify a DOM element when instantiating a view what happens?

A

Backbone will create a div element automatically, however, it is not inserted into the HTML by default - it’s simply in memory.

62
Q

If we don’t pass the DOM element to the instance of the view at the start, how can we get the data within it to display on screen?

A
var songView = new SongView();
songView.render();

$(“#container”).html(songView.$el);

// We can use jQuery to get the in memory data from the views $el attribute.

63
Q

What happens if you don’t want the view to create a div by default?

A

You can use the attributes of the View object to specify tagName.

tagName: “span”

will create a span

64
Q

How do you add attributes to a DOM element when creating a view?

A
var SongView = Backbone.View.extend({
    attributes: {
        "data-genre": "Jazz"
    },
    render: function() {
        this.$el.html("Hello World");
        return this;
    }
});
65
Q

How do you add a className and ID to a DOM element when creating a view?

A
var SongView = Backbone.View.extend({
    className: "song"
    id: "Superman",
render: function() {
    this.$el.html("Hello World");
    return this;
} });
66
Q

Given Backbone supports method chaining in the render method - how could we rewrite this?

var songView = new SongView();
songView.render();
$(“#container”).html(songView.$el);

A
var songView = new SongView();
$("#container").html(songView.render().$el);

// NOTE we directly access $el attribute from the this value returned by render.

67
Q

How do you pass a model to a view?

A

When instantiating a SongView.

var songView = new SongView({ el: “#container”, model: song });

68
Q

How do you access the data of a model in the view?

A

In the render method of the view - you can call the data like this:

render: function() {
    this. $el.html(this.model.get("title"));

    return this;
}
69
Q

Why will the following code fail? and how do you fix it?

var SongsView = Backbone.View.extend({
    render: function() {
        this.model.each(function(song) {
            var songView = new SongView({ model: song });
            this.$el.append(songView.render().$el);
        });
    }
});
A

The this in the closure, has had a change of context - it will not reference what we hope it would (which would be the this of the render function (which in itself would be the this of the SongsView object).

var SongsView = Backbone.View.extend({

    render: function() {
        var self = this;
        this.model.each(function(song) {
            var songView = new SongView({ model: song });
            self.$el.append(songView.render().$el);
        });
    }
});

Fix it by storing a copy of this - which the closure has access to.

70
Q

How would you pass a collection of song models to a view?

A
When we create a collection of song models - 
var Song = Backbone.Model.extend();
var Songs = Backbone.Collection.extend({model: Song});
var songs = new Songs([
    new Song({ title: "Superman" }),
    new Song({ title: "Blackwidow" }),
    new Song({ title: "Gotta stick that bitch." })
    ]);

We can simple pass it to the model attribute of the view.

var songsView = new SongsView({ el: “#container”, model: songs });

71
Q

How do we register events in the view?

A

Create a hash of events in the view - along with the associated methods that react to those events.

var SongView = Backbone.View.extend({
    events: {
        "click": "onClick"
    },
    onClick: function() {
        console.log("Listen Clicked");
    },

…..

72
Q

How can we use more complex selectors to trigger events?

A

You can use any jQuery selector to select a DOM element to raise an event:

var SongView = Backbone.View.extend({
    events: {
        "click .bookmark": "onClickBookmark",
    },

// The above example uses a class to specify what DOM element is selected.

73
Q

When using generic event handlers (i.e. just “click”) the event is propagated to other event handlers in the chain - how can we prevent this (in situations when this is undesirable)?

A

onClickBookmark: function(e) {
e.stopPropagation();

    // Do other code here
}
// NOTE that this was added to the more specific version of the click handler - it will then not propagate to the ones that were added before this - i.e. the more generic handler.
74
Q

What are the two methods that a web application can typically determine if a model has changed state?

A

Polling - Client checks periodically if the model has changed
Pushing - server tells client something has changed

75
Q

Why does Backbone require you to use set and get to change attribute values?

A

This is because attributes are stored in a hash, and not directly on the object as attributes. This was done so that they can effectively determine when the model has changed - something that would be difficult if it wasn’t stored as a hash.

76
Q

How do we configure a view to listen to a models ‘change’ event?

A
var SongView = Backbone.View.extend({
    initialize: function() {
        this.model.on("change", this.render, this);
    },

// Note the first parameter is the event name, the second is the function to call, the third is the context that that function should be called with (i.e. settings it’s this value).

77
Q

How could we write this code shorter?

this.$el.find(“li#” + song.id).remove();

A

this.$(“li#” + song.id).remove();

// NOTE Every view has a $ variable that is scoped to the view.

78
Q

Backbone collections raise what events when models are added / removed?

A

add

remove

79
Q

Underscore.JS can be used for templating HTML, what is the catch with regards to models?

A

Underscore does not know about backbone.js models. It will require JSON.

model.toJSON()

80
Q

How do you create a template for underscore.js?

A

Use the script tag in HTML.

    <script id="songTemplate" type="text/html">
        <%= title %>
        <button>Listen</button>
    </script>
81
Q

How do you parse the template in the backbone model?

A

var template = _.template($(“#songTemplate”).html());

Grab the template from the page - using the jQuery selectors - and using the HTML method to grab the actual html template. Then using the underscore method _.template - parse the data.

Then you can use the template method to take the model data and display it.

var html = template(this.model.toJSON());

82
Q

underscore templates should have what script type?

A

text/html

83
Q

How does underscore differentiate between a scripting element and an element that is intended to be filled with data from the model?

A

The element that is going to be replaced with data from the model will have a %= sign.

84
Q

How do you do a conditional statement in underscore templating?

A

<% if { %>
Do stuff
<% } %>

85
Q

If you have created an attributes field on a view - how can you populate those attributes from a model when they are added?

A

Create an attributes function callback that returns the values from the model.

attributes: function() {
    return {
        id : this.model.get('vehicleId'),
        "data-color": this.model.get('color')
    };
},
86
Q

On a view collection - how do you setup an event that will allow you to register when a button has been clicked for an individual model within the collection of views?/

A

events: {
“click .delete”: “onClickDelete”
},

    onClickDelete: function(ev) {
        var id = $(ev.currentTarget).attr("id");
        this.$("li#" + id).remove();
    },
87
Q

What is passed to the method described in the events block (i.e. the event parameter)?

A

It is an object which contains a number of useful fields. The currentTarget is the most useful.