1

I'm trying to understand the backbone bindAll function in addition to handling its contexts. In this case, the following implementation doesn't work.

  1. Create a view to insert data from a list.

  2. _.bindAll (this, 'render'); Could you see the context of this in the function do? $(this.el) is undefined. Shouldn't it work using _bindAll?

  3. The following does not append in the ol list

    $(this.el).append('idCurso->', cursoModelo.get('idCurso'),' titulo-> ', cursoModelo.get('titulo'));
    $(this.el).append('hola caracola');`. 
    

HTML

<ol id="ListaLibros"/>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>

JS

// create a view to print the model data in the html
var ListaLibrosView = Backbone.View.extend({
  el: '#ListaLibros',
  initialize: function() {
    this.collection = cursoCollection;

    _.bindAll(this, 'render');

    this.render();
  },
  render: function() {
    console.log("funcion render");
    var listaLibrosLi = '';

    this.collection.each(function(cursoModelo) {
      $(this.el).append('idCurso->', cursoModelo.get('idCurso'), ' titulo-> ', cursoModelo.get('titulo'));
      $(this.el).append('hola caracola');
    });
  }
});
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
user1358518
  • 93
  • 2
  • 13
  • Please format the code properly before posting... – T J Aug 03 '17 at 12:55
  • 1
    Don't say `$(this.el)` when you can say `this.$el`. Backbone caches the jQuery-wrapped `el` in [`$el`](http://backbonejs.org/#View-$el) so you should use it. – mu is too short Aug 03 '17 at 17:23

2 Answers2

2

You're not using using this.el directly inside render, but inside a _.each() callback, which is another function with different context. You need to make sure it has the same context as well, you can simply achieve it like _.each(function(){}, this) since it accepts the context as second argument.

Or if you're using ES6 you can use an arrow function as callback which does not create a new context like _.each(i => {})

T J
  • 42,762
  • 13
  • 83
  • 138
2

TJ's right, though you're using this.collection.each, it's just a proxy to Underscore's _.each.

Also, this.$el = $(this.el). You should use this.$el directly.

Note that _.bindAll is an Underscore's function and it is unrelated to Backbone. Since the problem comes from the nested each callback context, once fixed, you won't need _.bindAll at all.

In fact, I never needed _.bindAll and when seen in tutorials, most of the time, it's because it's outdated or wrongly used.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129