似乎无法将功能绑定到骨干网中的视图.js

Cannot seem to bind function to view in backbone.js

本文关键字:骨干网 视图 js 绑定 功能      更新时间:2023-09-26

我想将checkScroll()绑定到视图PhotoListView,以便我可以从$(Window).scroll()内部调用this.checkScroll(),而无需先var self = this然后调用self.checkScroll()

问题:但是绑定似乎不起作用,我收到错误Uncaught TypeError: Object [object Window] has no method 'checkScroll'我是否绑定错误?

视图

PhotoListView = Backbone.View.extend({
    el: '#photo_list',
    initialize: function() {
        _.bindAll(this, 'checkScroll');
        this.bind('checkScroll', this)
        $(window).scroll(function() {
            this.checkScroll();
        });
    },
    checkScroll: function() {
        console.log('checkScroll');
    }
});

是的,试试这个:

initialize: function() {
    _.bindAll(this, 'checkScroll');
    $(window).scroll(this.checkScroll)
},

_.bindAll将采用this.checkScroll并将其上下文固定为 this ,因此您可以直接将其作为处理程序传递。但是你通过使用匿名函数把它扔掉了。

请注意,"绑定"有 2 个不同的概念:

  • 将函数绑定到对象,以便无论如何调用该函数,它都将具有固定的this
  • 将处理程序附加到元素的事件

_.bindAll前者。


JSFIDDLE 演示

尝试:

var view = this; //add this
$(window).scroll(function() {
    view.checkScroll(); //change "this" to "view"
});

代码的实际问题是丢失this上下文。通过删除内联函数并提供对该函数的直接引用,您可以避免在闭包上丢失上下文。

但是,如果您仍想使用内联函数或执行一系列函数,您仍然可以使用相同的代码,使用公开适当上下文的代理包装函数。

您必须代理函数并为其提供适当的范围:

使用下划线:

$(window).scroll(_.bind(function() {
    this.checkScroll();
    this.anotherFunction();
},this));

使用 jQuery:

$(window).scroll($.proxy(function() {
    this.checkScroll();
    this.anotherFunction();
},this));