Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

listenTo not working when using in another view in backbone.js

Tags:

backbone.js

I am a newbee 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");
    }
});

With abc.js click event is triggering fine. But with xyz.js click event is not triggering.

Is this the correct way to call listenTo.

like image 261
Cindrella Avatar asked Jun 03 '13 12:06

Cindrella


2 Answers

DOM events aren't delegated on the View object.

If you want to emulate this though, you'd have to manually emit the event in ABC display method:

display: function(e){

    // Trigger manually
    this.trigger("click");

    // Your usual code
    console.log("hello");
    alert("click function");
}

In term of best practice, I'd probably rename "click" to a more descriptive event name.

like image 149
Simon Boudrias Avatar answered Nov 19 '22 06:11

Simon Boudrias


Backbone's on and listenTo are intended for listening to events on Backbone Models and Collections.

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

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

That being said, you can use something like what Simon suggests to intermingle the two.

like image 24
Bart Avatar answered Nov 19 '22 05:11

Bart