使用骨干渲染bootstrap模式

我认为代码会更好地解释我的问题:视图:

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; } }); 

实例化时:

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

模态已加载,但我只得到一个空div

谢谢您的帮助! 罗伊

最好创建一个包含所有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 } }); 

把手模板

  

父视图 //按钮点击后触发

 modalView = new BaseModalView(); modalView.show(); // Modal view automatically bound to the body and removes itself on hidden; 

一个简单的引导模式 –

我们可以扩展此视图以向其添加更多function。 我们也可以在init上传递数据。

查看文件

 /** * ModalView * @version 0.0.1 */ var ModalView = Backbone.View.extend({ tpl: JST['modal-tpl'], className: 'modal-view', events: { 'evt:show': 'show', 'evt:hide': 'hide', }, initialize: function(options) { this.options = options; _.bindAll(this, 'render', 'show', 'hide', 'remove'); this.render(); }, render: function() { this.$el.html(this.tpl(this.options)); this.$el.appendTo('body'); this.$modal = this.$('.modal'); this.$modal.on('hidden.bs.modal', _.bind(function() { this.close(); }, this)); }, show: function() { this.$modal.modal('show'); }, hide: function() { this.$modal.modal('hide'); }, close: function() { //unbind events this.unbind(); //Remove html from page this.remove(); }, }); 

打开模态 –

 //Pass modal data on init var modal = new ModalView({ modalContent: 'Hello User!' }); modal.show(); //modal.trigger('evt:show'); 

v3的车把模板 –

   
  • 关于模态隐藏 – 我们必须删除模态html,事件以避免多个实例。
  • Bootstrap模态HTML应该附加到正文 – 如果不是,您可能会遇到z-index / backdrop的问题。

看起来你永远不会将它添加到页面。

 var errorModal = new App.Views.ErrorModal({model: error}); $('#my-div').html(errorModal.el); errorModal.render(); 

我假设bootstrap-modal,就像大多数jquery插件一样,在调用之前需要html在页面上。

尝试从模态视图中删除淡入淡出并隐藏类。