gpt4 book ai didi

javascript - 在 Backbone 绑定(bind)中不正确

转载 作者:行者123 更新时间:2023-11-30 18:02:01 26 4
gpt4 key购买 nike

 DM.Backbone.View.feedback = Backbone.View.extend( {
initialize: function (){
this.render( this.model.get( 'data' ) || [] );
},
render: function ( param ){
if ( $( '.problem_report_reply' ).length > 0 ) {
_.bind( this.mail_to, this );
$( '.problem_report_reply' ).off().on( 'click', this.mail_to )
}
},
mail_to: function (){

console.log( 'this', this )
} );

这是我的 Backbone.View 代码。我对 DOM 元素的绑定(bind)方法有问题,console.log 将其显示为我单击的 DOM 元素。我使用 undescore 方法 _.bind 来纠正绑定(bind) this,有什么问题吗?

最佳答案

_.bind创建一个新函数,它不会修改现有函数。你可以像这样使用它

render: function ( param ){
var func;

if ( $( '.problem_report_reply' ).length > 0 ) {
func = _.bind(this.mail_to, this);
$('.problem_report_reply').off().on('click', func);
}
}

或者使用_.bindAll , 它确实修改了对象中的函数

DM.Backbone.View.feedback = Backbone.View.extend({
initialize: function (){
_.bindAll(this, "mail_to");
this.render( this.model.get( 'data' ) || [] );
},
render: function ( param ){
if ( $( '.problem_report_reply' ).length > 0 ) {
$( '.problem_report_reply' ).off().on('click', this.mail_to)
}
},
mail_to: function (){
console.log( 'this', this )
}
});

关于javascript - 在 Backbone 绑定(bind)中不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16733870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com