Cindrella
Cindrella

Reputation: 1721

listenTo not working when using in another view in 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.

Upvotes: 5

Views: 3939

Answers (2)

Bart
Bart

Reputation: 6814

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.

Upvotes: 3

Simon Boudrias
Simon Boudrias

Reputation: 44609

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.

Upvotes: 4

Related Questions