Feature view calls from subview with BackboneJS

I would like to know if it is possible to call the view function from the subtitle using BackboneJS. If so, how does it work?

I want to call the "hello" function, which belongs to mainView from the view.

Maybe if the event is triggered ...

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!

+6
source share
2 answers

You can pass the link from your parent view to the subtitle:

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); 
+8
source

You can try expanding MainView as follows:

var SubView = MainView.extend({ });

This will then give you a reference to the hello function in MainView .

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

 MainView.prototype.hello.call(this) 

This will call the hello function in MainView using the context (template, other bars, etc.) of the SubView instance.

+2
source

Source: https://habr.com/ru/post/944471/


All Articles