Events BackboneJS从绑定到集合的事件调用视图渲染函数
我尝试了许多不同的方法从modeladded:的代码中调用views render:方法。使用this.render inside model added表明该点上的this对象没有渲染功能。我还试着以如下方式传递视图: this.collection.bind('add',this.modelsadded(this)) 新增模型:功能(视图){ view.render() 这也会导致控制台错误,即找不到render()。有人知道如何调用视图render:from inside modeladded吗 目前,我将render函数从views render:中移到了一个JavaScript函数中,该函数在全局范围内声明为renderGlobal(),我知道它确实是这样工作的,但我认为这不是backbone.js真正的方式 这是控制台中出现的错误: 未捕获的TypeError:对象[Object Object]没有方法“render”Events BackboneJS从绑定到集合的事件调用视图渲染函数,events,backbone.js,collections,render,backbone-events,Events,Backbone.js,Collections,Render,Backbone Events,我尝试了许多不同的方法从modeladded:的代码中调用views render:方法。使用this.render inside model added表明该点上的this对象没有渲染功能。我还试着以如下方式传递视图: this.collection.bind('add',this.modelsadded(this)) 新增模型:功能(视图){ view.render() 这也会导致控制台错误,即找不到render()。有人知道如何调用视图render:from inside modeladd
感谢您发布…您正在使用以下方式绑定事件处理程序: 但是,与JavaScript一样,函数中
this
的值取决于函数的调用方式,而不是函数的定义方式(当然忽略绑定函数)。您没有在任何地方为函数指定特定的this
,因此在调用时不会得到任何特定的this
。如果您提供bind
第三个上下文参数:
this.collection.bind('add', this.modeladded);
然后主干将使用特定的this
调用modelsadded
,您将发现this
内部modelsadded
将是您的视图
您还可以使用或生成回调的绑定版本:
this.collection.bind('add', this.modeladded, this);
// ------------------------------------------^^^^
所有这些都会生成新函数,因此如果不将绑定函数隐藏在某个位置,您将无法使用这些函数。当您可以选择显式指定上下文(AKAthis
)时,通常会避免使用这些函数
还有:
listenToobject.listenTo(其他、事件、回调)
告诉对象侦听其他对象上的特定事件。使用此表单而不是other.on(事件、回调、对象)的优点
,即listenTo允许对象跟踪事件,并且可以在以后一次删除所有事件。调用回调时始终使用对象作为上下文
所以你可以(也应该)说:
this.collection.bind('add', _(this.modeladded).bind(this));
this.collection.bind('add', this.modeladded.bind(this));
this.collection.bind('add', $.proxy(this.modeladded, this));
这将为您提供所需的此
,并使您在处理完事件处理程序后更容易清理它们。同样,您正在使用的其他事件处理程序也是如此
this.collection.bind('add', _(this.modeladded).bind(this));
this.collection.bind('add', this.modeladded.bind(this));
this.collection.bind('add', $.proxy(this.modeladded, this));
this.listenTo(this.collection, 'add', this.modeladded);