Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(){
    this.$el.html(this.template(this.model.toJSON()));

    this.$("#errorApproveModal").modal({
        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});
 errorModal.render();

The modal is loaded but i get only an empty div

Thanks for the help! Roy

like image 302
royB Avatar asked Apr 18 '13 14:04

royB


1 Answers

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');
      this.render();
    },

    show: function() {
      this.$el.modal('show');
    },

    teardown: function() {
      this.$el.data('modal', null);
      this.remove();
    },

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

    renderView: function(template) {
      this.$el.html(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>
    <div class="modal-body">
      ...
    </div>
    <div class="modal-footer">
      <a href="#" class="btn">Close</a>
      <a href="#" class="btn btn-primary">Save changes</a>
    </div>
  </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

Parent View // on button click following fired

modalView = new BaseModalView();
modalView.show();

// Modal view automatically bound to the body and removes itself on hidden;
like image 157
Andrew Shatnyy Avatar answered Oct 27 '22 10:10

Andrew Shatnyy