我正在尝试理解骨干bindAll
函数以及处理其上下文。在这种情况下,以下实现不起作用。
创建一个视图以从列表中插入数据。
_.bindAll (this, 'render');
你能在函数中看到这个的上下文吗? $(this.el)
是undefined
。它不应该使用_bindAll
吗?
以下内容未附加在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');
});
}
});
答案 0 :(得分:2)
您未在this.el
内直接使用render
,而是在_.each()
回调中使用,这是另一个具有不同上下文的函数。您需要确保它具有相同的上下文,您可以像_.each(function(){}, this)
一样实现它,因为它接受上下文作为第二个参数。
或者,如果您正在使用ES6,则可以使用箭头功能作为回调,但不会创建新的上下文,例如_.each(i => {})
答案 1 :(得分:2)
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,它与Backbone无关。由于问题来自嵌套的每个回调上下文,一旦修复,您根本不需要_.bindAll
。
事实上,我从不需要_.bindAll
,而且在教程中看到,大部分时间都是因为它过时或使用不当。