royB royB - 9 months ago 107
jQuery Question

Rendering bootstrap modal using backbone

I think a code will explain better my problem:
the View:

App.Views.ErrorModal = Backbone.View.extend({
template: window.template('errorModal'),

render: function(){

keyboard: true

return this;



when instantiating:

var error = new App.Models.Errors({title: "Exporting Error", content: "Error"});
var errorModal = new App.Views.ErrorModal({model: error});

The modal is loaded but i get only an empty div

Thanks for the help!

Answer Source

It always better to create a separate class that holds all Modal logic and then call it from the master view.

Try using this approach.

Modal JS

var BaseModalView = Backbone.View.extend({

    id: 'base-modal',
    className: 'modal fade hide',
    template: 'modals/BaseModal',

    events: {
      'hidden': 'teardown'

    initialize: function() {
      _.bindAll(this, 'show', 'teardown', 'render', 'renderView');

    show: function() {

    teardown: function() {
      this.$'modal', null);

    render: function() {
      this.getTemplate(this.template, this.renderView);
      return this;

    renderView: function(template) {
      this.$el.modal({show:false}); // dont show modal on instantiation

Handlebars template

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      <h4 class="modal-title">Modal title</h4>
    <div class="modal-body">
    <div class="modal-footer">
      <a href="#" class="btn">Close</a>
      <a href="#" class="btn btn-primary">Save changes</a>
  </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

Parent View // on button click following fired

modalView = new BaseModalView();;

// Modal view automatically bound to the body and removes itself on hidden;