【问题标题】:_.bindAll isn't working while rendering a Backbone view_.bindAll 在渲染主干视图时不起作用
【发布时间】:2017-08-03 10:43:38
【问题描述】:

除了处理其上下文之外,我还试图了解主干bindAll 函数。在这种情况下,以下实现不起作用。

  1. 创建一个视图以从列表中插入数据。

  2. _.bindAll (this, 'render');你能在函数中看到this的上下文吗? $(this.el)undefined。不应该使用_bindAll 工作吗?

  3. 以下内容不会添加到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');
    });
  }
});

【问题讨论】:

  • 请在发布前正确格式化代码...
  • 当你可以说this.$el时不要说$(this.el)。 Backbone 将 jQuery 包装的 el 缓存在 $el 中,因此您应该使用它。

标签: javascript backbone.js


【解决方案1】:

您不是在render 中直接使用this.el,而是在_.each() 回调中使用,这是另一个具有不同上下文的函数。您需要确保它也具有相同的上下文,您可以像 _.each(function(){}, this) 一样简单地实现它,因为它接受上下文作为第二个参数。

或者,如果您使用的是 ES6,您可以使用箭头函数作为回调,它不会创建像 _.each(i =&gt; {}) 这样的新上下文

【讨论】:

    【解决方案2】:

    TJ's right,尽管您使用的是 this.collection.each, it's just a proxyUnderscore's _.each

    另外,this.$el = $(this.el)。你应该直接使用this.$el

    请注意,_.bindAll is an Underscore's function 与 Backbone 无关。由于问题来自嵌套的每个回调上下文,一旦修复,您根本不需要_.bindAll

    事实上,我从来不需要_.bindAll,当在教程中看到时,大多数时候是因为它已经过时或使用错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多