从嵌套函数访问外部对象(使用backbone.js

时间:2011-05-17 18:45:30

标签: javascript backbone.js

我正在使用backbone.js构建一个js繁重的应用程序。我遇到的一个问题是如何从深层嵌套函数调用外部对象。在下面的代码示例中,我想在发生幻灯片事件时调用custom_function事件。这样做的最佳方式是什么?

App.Views.Category = Backbone.View.extend({
    ....,
    render: function () {

        $('#slider').slider({
            min:0,
            max:100,
            slide: function(event, ui) {
               //HOW DO I CALL THE custom_function from here????

            },

        });
    },

    custom_function: function() {
       alert('in custom function');
    },


});

ASDF

1 个答案:

答案 0 :(得分:2)

有两种常见的选择。

您可以this加入thatself这样的对象,然后调用它。

render: function () {
    var that = this;
    $('#slider').slider({
        min:0,
        max:100,
        slide: function(event, ui) {
           //HOW DO I CALL THE custom_function from here????
           that.custom_function();
        },

    });
},

或者你可以绑定函数的上下文。

render: function () {
    $('#slider').slider({
        min:0,
        max:100,
        slide: (function(event, ui) {
           //HOW DO I CALL THE custom_function from here????
           this.custom_function();
        }).bind(this),

    });
}, 

Function.prototype.bind仅限ES5,因此使用_.bind$.proxy进行跨浏览器支持

相关问题