使用Backbone.js创build一个模态

我是Backbone的新手,虽然我做了一些研究,但在创buildModal方面,找不到解决scheme。 我想创build一个基础Modal类,然后重用/扩展它,并在我的其他视图/类中应用不同的模板。

这是我的Modal基类:

define([ // Application. 'app', 'backbone', 'plugins/jquery-ui.custom', 'moment' ], function(App, Backbone) { // Create a new module. var Modal = App.module(); Modal.View = Backbone.View.extend({ className: 'ui-modal', render: function () { console.log('this.$el',this.$el,'this.template',this.template); this.$el.html(this.template()); this.$el.delegate('.close', 'click', this.closeModal); this.error = this.$el.find('.error'); return this; }, closeModal: function (ev) { if (ev) ev.preventDefault(); this.$el.unbind(); this.$el.empty(); this.$el.remove(); }, initialize: function () { console.log('initialize modal view', 'this.$el', this.$el); _.bindAll(this, 'render', 'closeModal'); return Backbone.View.prototype.initialize.call(this); } }); 

我想在这里扩展/使用Modal类:

 ProductDetails.Views.testView = Modal.View.extend({ template: 'modals/ProductDetails/testView', render: function() { Modal.View.prototype.render.call(this); this.delegateEvents(); return this; }, initialize: function() { console.log('initialize testView','this.$el',this.$el); return Modal.View.prototype.initialize.call(this); } }); 

然后我试着在这里触发Modal:

 ProductDetails.Views.Description = Backbone.View.extend({ template: 'partials/product/description', initialize: function(){ _.bindAll(this, 'serialize', 'warn', 'error', 'updateModel', 'testModalView'); //instantiate the test modal this.testView = new ProductDetails.Views.testView(); this.testView.$el = this.$el; }, serialize: function(){ //some stuff }, events: { 'click .testModalView_link': 'testModalView' //some other stuff }, warn: function() { //some stuff }, error: function(error){ //some stuff }, updateModel: function(e){ //some stuff }, testModalView: function(ev) { try { ev.preventDefault(); $('.ui-modal').append(this.testView.render()) } catch(e) { console.log(e.message,e); } } }); 

我已经加倍检查,但是我可能在尝试简化包含在这个问题中的代码时犯了一个错误。 当我通过点击链接(class .testModalView_link)testing我的模态时,出现错误:“TypeError:this。$ el is undefined”,它指向模态基类,在这一行:

 this.$el.html(this.template()); 

任何人都可以帮我做这个工作,或者至less明白我做错了什么?

谢谢。

谢谢您的帮助。 我将从这个问题上继续,我花了很多时间去debugging它,甚至考虑另外的实现; 最后我相信这个问题是我们加载和编译模板的方式,或者是我们使用的库/插件的版本。 我也注意到,类似的问题发生在DOM没有完全加载,或元素被呈现之前被访问; 再次,也可能是绑定和callback,范围没有得到妥善处理。 如果我重新审视这个问题并发现它的可靠答案,我一定会提供一个更新。