【发布时间】:2014-10-04 07:01:40
【问题描述】:
我是 Backbone 的新手,虽然我做了一些研究,但在创建模态框方面我找不到适合我的解决方案。我想创建一个基础 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);
}
});
然后我尝试在这里触发模态:
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);
}
}
});
我已经仔细检查过,但在尝试简化代码以包含在此问题中时,我可能犯了一个错误。当我通过单击链接(使用类 .testModalView_link)测试我的模式时,我收到错误:“TypeError:this.$el is undefined”,它指向模式基类,指向这一行:
this.$el.html(this.template());
谁能帮我完成这项工作,或者至少了解我做错了什么?
谢谢。
【问题讨论】:
-
我在 jsfiddle 上试了一下,它似乎工作正常。 Fiddle here
-
那时我很困惑 :) 感谢您的帮助
-
它实际上声明 this.$el 在 testModal.render() 中是未定义的,然后在到达 Modal.View.render() 时再次声明。但是,我测试了 testModal.beforeRender(),console.log 为 this.$el 输出了错误的 DIV,所以我猜我正在处理范围问题。
-
你能创建一个重现问题的小提琴吗?
-
我无法为您创建 Fiddle。您的 Fiddle 和我的 Fiddle 之间的区别在于,我需要使用 require.js 和 Lo-Dash,并且会通过其路径引用模态模板,而不是通过预加载模板中的 JQuery。
标签: javascript jquery node.js backbone.js express