maximus
maximus

Reputation: 4302

backbone.js: code for calling function from nested view doesn't work

I have made the following code, which runs without errors, but after I press the button, it makes an error: tabClicked is not defined.

var MainView = Backbone.View.extend({
    initialize: function() {

    },

    tabClicked: function(winID) {
         alert("test");
    }
});

var BottomPanel = MainView.extend( {
    initialize: function() {
        $("body").append($(this.el));
        this.$el.attr("id", "bottomPanel").attr("top", "300px").attr("left", "50px");
        this.$el.append($("<button>").click(this.func1));
    },
    func1: function() {
        tabClicked(0);
    }
});

$(document).ready(function() { 
    var mainView = new MainView();
    var bottomPanel = new BottomPanel();
});

I made a child window "BottomPanel" of the parent window "MainView". And my intention was to call a method of MainView from BottomPanel Object. How to do it?

EDIT 1: I have changed the code above in one line:

this.$el.append($("<button>").click(this.tabClicked));

Now it works, but I need to save the context. Now this variable when button is clicked points not to the mainView object.

Upvotes: 2

Views: 142

Answers (1)

chchrist
chchrist

Reputation: 19802

It should be this.tabClicked() otherwise javascript looks at the global namespace where tabClicked is not defined.

Upvotes: 2

Related Questions