Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call view function from subview with BackboneJS

I'd like to know if it's possible to call a view function from a subview with BackboneJS. If yes, how it's working?

I want to call the function "hello" which belong to the mainView from the subview.

Maybe if event triggering...

Example:

var MainView = Backbone.View.extend({

    initialize: function() {
        this.$template = $(template);
        this.subview = new SubView();               
        this.render();              
    },

    render: function() {
        this.$el.html(this.$template);
        var element = this.$template.attr('id');
        this.subview.setElement('#'+element).render();
    },

    hello: function() {
        alert('Hello');
    }

});


var SubView = Backbone.View.extend({

    initialize: function() {
        this.$template = $(template);           
        this.render();              
    },

    render: function() {
        this.$el.html(this.$template);
        //Call view function ' hello '
        //parentView.hello();
    }

});

Thanks!

like image 788
alexmngn Avatar asked May 07 '13 19:05

alexmngn


2 Answers

You can pass a reference from your parent view to your subview:

http://jsfiddle.net/puleos/hecNz/

var MainView = Backbone.View.extend({

    initialize: function() {
        this.$template = $("<span>foo</span>");
        this.subview = new SubView({parent: this});               
        this.render();              
    },

    render: function() {
        this.$el.html(this.$template);
        var element = this.$template.attr('id');
        this.subview.setElement('#'+element).render();
    },

    hello: function() {
        alert('Hello');
    }

});


var SubView = Backbone.View.extend({

    initialize: function(options) {
        this.$template = $("<span>bar</span>");
        this.parent = options.parent;
        this.render();              
    },

    render: function() {
        this.$el.html(this.$template);
        this.parent.hello();
    }

});

var mainView = new MainView();

console.log(mainView);
like image 181
Scott Puleo Avatar answered Oct 14 '22 00:10

Scott Puleo


You can try extending the MainView like this:

var SubView = MainView.extend({ });

That should then give you a reference to the hello function within MainView.

Or, in SubView, add this to your render function:

MainView.prototype.hello.call(this) 

That would call the hello function in MainView using the context (template, other vars, etc) of the SubView instance.

like image 37
Marty Cortez Avatar answered Oct 14 '22 01:10

Marty Cortez