ham*_*son 2 javascript backbone.js
无法让下面的代码工作.
我试图从具有自己的事件对象的渲染子视图中触发事件.
是否有可能以简单的方式做到这一点?
var SubView = Backbone.View.extend({
events: {
'click .subview-item a': 'test'
},
el: '#subview',
test: function() {
console.log('please print this...');
},
initialize: function() {
this.template = '<div class="subview-item"><a href="#">Clickable Subview</a></div>'
},
render: function(){
$(this.el).html(_.template(this.template));
return this;
}
});
var MainView = Backbone.View.extend({
el: $('#content'),
initialize: function(){
this.template = '<h1>Hello</h1><div id="subview"></div>';
this.subView = new SubView();
},
render: function(){
$(this.el).html(_.template(this.template));
this.subView.render();
return this;
}
});
var mainView = new MainView({});
mainView.render();
Run Code Online (Sandbox Code Playgroud)
有任何想法吗??
当您创建subView
内MainView
的initialize
,该#subview
元素不存在DOM中的,因为你还没有渲染的MainView.所以在DOM 之外<div>
创建一个new .您需要先创建,然后再创建.你可以做内部的,但下面是简单的,我认为:MainView
SubView
MainView
render()
var SubView = Backbone.View.extend({
events: {
'click .subview-item a': 'test'
},
el: '#subview',
test: function() {
console.log('please print this...');
},
initialize: function() {
this.template = _.template('<div class="subview-item"><a href="#">Clickable Subview</a></div>');
},
render: function() {
this.$el.html(this.template);
return this;
}
});
var MainView = Backbone.View.extend({
el: $('#content'),
initialize: function() {
this.template = _.template('<h1>Hello</h1><div id="subview"></div>');
},
render: function() {
this.$el.html(this.template);
return this;
}
});
var mainView = new MainView();
mainView.render();
var subView = new SubView();
subView.render();
Run Code Online (Sandbox Code Playgroud)
还冒昧地纠正了一些事情,比如使用this.$el
和创建模板initialize()
而不是重新编译每个模板render()
.
归档时间: |
|
查看次数: |
1991 次 |
最近记录: |