代码之家  ›  专栏  ›  技术社区  ›  user1358518

_.渲染主干视图时bindAll不工作

  •  1
  • user1358518  · 技术社区  · 7 年前

    bindAll 除了处理其上下文外,还具有其他功能。在这种情况下,以下实现不起作用。

    1. _.bindAll (this, 'render'); 你能看到函数do中的上下文吗? $(this.el) undefined _bindAll ?

    2. ol 列表

      $(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');
        });
      }
    });
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   T J    7 年前

    你没有使用 this.el 直接在内部 render _.each() _.each(function(){}, this) 因为它接受上下文作为第二个参数。

    _.each(i => {})

        2
  •  2
  •   Emile Bergeron Dhaval Rajpara    7 年前

    TJ's right ,尽管您正在使用 this.collection.each , it's just a proxy Underscore's _.each .

    this.$el = $(this.el) this.$el 直接地

    请注意 _.bindAll is an Underscore's function _.bindAll

    事实上,我从不需要 当在教程中看到时,大多数情况下,这是因为它过时或使用不当。