Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the `Backbone.View.events` definition to listen for custom subview events?

Is it possible to use the Backbone.View.events definition to listen for custom subview events?

Child definition

All click events are cached and trigger my clicked function:

var Child = Backbone.View.extend({
    events : {
        'click' : 'clicked'
    },
    clicked: function() {
       alert('View was clicked');
       this.trigger("customEvent");  
    },
    render: function() {
      this.$el.html("<span>Click me</span>");
    }
});

Parent definition

Why don't customEvent events call my action function?

var Parent = Backbone.View.extend({
    events : {
        'customEvent' : 'action'
    },
    action : function() {
       alert('My sub view triggered a custom event');  
    },
    render : function() {
      var child = new Child();
      this.$el.append(child.el);
      child.render();
    }
});

Create and render parent

var parent = new Parent();
parent.$el.appendTo(document.body);
parent.render();

jsfiddle example

I know that could use listenTo instead but using the events definition seems to be cleaner.

My intention is to build a sub view (e.g. a color picker) which triggers an event after it is done.

like image 311
jantimon Avatar asked Apr 07 '13 10:04

jantimon


1 Answers

Quick Notes:-

  • In events object of a view, we should not define custom events. For custom events we should do binding. Use either bind() method or listen to some event using on().
  • If your subview's el element is inside your parent view's el, you can directly listen to events on child's el too provided you are not returning false from child's event handler. Take a look at this: Code where parent view is listening event on element onside child view

If you want to use custom event only, You can see here Your Updated Fiddle

var Child = Backbone.View.extend({
    initialize: function(options) {
        this.parent = options.parent;
    },
    events : {
        'click' : 'clicked'
    },
    clicked: function() {
       alert('View was clicked');
       this.parent.trigger("customEvent");  
    },
    render: function() {
      this.$el.html("<span>Click me</span>");
    }
});

var Parent = Backbone.View.extend({
    initialize: function() {
        this.on('customEvent', this.action);
    },
    action : function() {
       alert('My sub view triggered a custom event');  
    },
    render : function() {
      var child = new Child({parent: this});
      this.$el.append(child.el);
      child.render();
    }
});

var parent = new Parent();
parent.$el.appendTo(document.body);
parent.render();
like image 79
Sachin Avatar answered Oct 21 '22 04:10

Sachin