ListenTo does not work when used in a different view in backbone.js

I am new to backbone. I have a view called AbcView abc.js

var AbcView = Backbone.View.extend({ events: { "click" : "display", }, display: function(e){ console.log("hello"); alert("click function"); } }); 

Now I am passing this abc.js to another xyz.js file and calling it in another view using ListenTo.

xyz.js

 var xyzView = Backbone.View.extend({ initialize: function(){ var AbcView = new AbcView (); this.lisenTo(AbcView, "click",this.display); }, render: function(){ var html = this.template(AbcView); this.$el.html(html); return this; }, display: function(e){ console.log("parent hello"); alert("parent display function"); } }); 

The abc.js click event triggers a penalty. But with the event xyz.js click does not fire.

This is the correct way to call listenTo.

+4
source share
2 answers

DOM events are not delegated in the View object.

If you want to emulate this, you must manually emit the event in the ABC display method:

 display: function(e){ // Trigger manually this.trigger("click"); // Your usual code console.log("hello"); alert("click function"); } 

At best, I will probably rename "click" to a more descriptive name for the event.

+2
source

The on and listenTo are for listening to events on Backbone Models and Collections .

http://backbonejs.org/#Events-catalog

This is important to understand. This is not the same as a UI event binding, as described in http://backbonejs.org/#View-delegateEvents .

Having said that, you can use something like Simon suggests mixing two.

+3
source

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


All Articles