Q & A

In notebook:
FrontEndMasters BackboneJS
Created at:
2016-05-29
Updated:
2016-05-29
Tags:
JavaScript Fundamentals
What is the ​this​ in the code?

(​debugger​ is great for adding a breakpoint in the browser debugger.)
Adds the ​debugger​ to the ​initialise​ method.
  var CommentModel = Backbone.Model.extend({
  initialize: function(){
    debugger,
  },
  validate: function(attrs){
    ...
  }
});
At this point the ​this​ references the model instance itself. It also has a number of other properties like collection that references the parent collection.

One gotcha, is when you create an anonymous function. It will be scoped to the global scope. Also jQuery steals the ​this​ element.
You can use ​bind​ and to pass the correct context. 
Or use the ​var self = this;​ to save the value of self.
- What’s the logic of storing the commentview on the model?
This way you have means to manage a collection of views. Normally backbone manages only collections of models.
  //...
renderComment: function (model){
  model.view = new CommentView({model: model});
  var comment = model.view.render();
  //...
}
We can call methods on it like ​comment.collection.first().view.remove()​. (In the console of the browser for example)
If you have multiple views, it’s not practical.
Normally the model is not required to have a reference to the view. 

Can stop garbage collection from happening! [referencing views in the model]