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

Can I use a definition Backbone.View.eventsto listen to custom preview events?

Baby definition

All events clickare cached and trigger my function clicked:

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 customEventdidn't events call my function action?

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 display parent

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

Jsfiddle example

I know that it can be used instead listenTo, but using event definition seems cleaner.

My intention is to create an additional view (for example, a set of colors) that fires an event after its completion.

+5
source share
1

: -

  • . . bind() - , on().
  • subview el el, el, false . : , onside

,

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();
+9

All Articles