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!
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With