繁体   English   中英

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

[英]Accessing an outer object from a nested function (Using 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

有两种常见的选择。

你可以把this变成这样的对象that也可以self调用它。

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进行跨浏览器支持

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM