hampusohlsson
hampusohlsson

Reputation: 10219

Backbone.js firing event from a view inside a view

Have som trouble getting the code below to work.

I am trying to fire an event from a rendered sub view that has its own events object.

Is it possible to do this in an easy way?

var SubView = Backbone.View.extend({
    events: {
      'click .subview-item a': 'test'
    },
    el: '#subview',
    test: function() {
      console.log('please print this...');
    },
    initialize: function() {
      this.template = '<div class="subview-item"><a href="#">Clickable Subview</a></div>'
    },
    render: function(){
      $(this.el).html(_.template(this.template));
      return this;
    }
});

var MainView = Backbone.View.extend({
    el: $('#content'),
    initialize: function(){
      this.template = '<h1>Hello</h1><div id="subview"></div>';
      this.subView = new SubView();
    },
    render: function(){
      $(this.el).html(_.template(this.template));
      this.subView.render();
      return this;
    }
});

var mainView = new MainView({});
mainView.render();

Any ideas??

Upvotes: 2

Views: 2001

Answers (1)

ggozad
ggozad

Reputation: 13105

When you create your subView inside MainView's initialize, the #subview element does not yet exist in your DOM, since you have not yet rendered MainView. So a new <div> is created outside the DOM. You need to first render MainView before creating the SubView. You could do that inside the MainView's render() but the following is simpler I think:

var SubView = Backbone.View.extend({
    events: {
        'click .subview-item a': 'test'
    },
    el: '#subview',
    test: function() {
        console.log('please print this...');
    },
    initialize: function() {
        this.template = _.template('<div class="subview-item"><a href="#">Clickable Subview</a></div>');
    },
    render: function() {
        this.$el.html(this.template);
        return this;
    }
});

var MainView = Backbone.View.extend({
    el: $('#content'),
    initialize: function() {
        this.template = _.template('<h1>Hello</h1><div id="subview"></div>');
    },
    render: function() {
        this.$el.html(this.template);
        return this;
    }
});

var mainView = new MainView();
mainView.render();
var subView = new SubView();
subView.render();

Also took the liberty to correct a few things like using this.$el and creating the template on initialize() rather than recompiling on every render().

Upvotes: 6

Related Questions