Backbone js - 动态加载视图: el 应该是启动器,还是应该由父视图启动?
我有一个关于动态加载视图元素上的 el 标签的问题。我将一个点击侦听器附加到 标记,该标记将动态加载视图元素(从模板渲染它,通过 ajax 填充一些内容等)。现在我已经实现它如下:
MyDynamicView = Backbone.View.extend({
el: "a#dynamic-launcher",
events: {
"click": "launch"
},
initialize: function(){
_.bindAll(this, "render");
},
launch: function(e){
e.preventDefault();
this.render();
},
render: function(){
// do template/ajax/whatever.
}
});
效果相当好,但它确实阻止我做一些事情。例如,如果我想添加另一个事件,该事件是由新动态视图中的某些内容触发的,我就无法做到这一点(因为这些事件仅在父 el
下方查看)。
因此,另一种选择可能是拥有一个父视图,它知道哪个元素启动动态元素,然后创建/渲染它。
velo.AppView = Backbone.View.extend({
el: "body",
events: {
"click a#dynamic-launcher": "launchDynamicView"
},
launchDynamicView: function(e){
e.preventDefault();
new MyDynamicView(); // Or something - Maybe I need to call render. Not sure.
}
});
第二种技术更有意义吗?
任何指导都会很棒!
谢谢。
I have a question about the el tag on a dynamically loading view element. I'm attaching a click listener to an <a>
tag, which will dynamically load the view element (render it from a template, populate some content over ajax etc.). Now I have currently implemented it as follows:
MyDynamicView = Backbone.View.extend({
el: "a#dynamic-launcher",
events: {
"click": "launch"
},
initialize: function(){
_.bindAll(this, "render");
},
launch: function(e){
e.preventDefault();
this.render();
},
render: function(){
// do template/ajax/whatever.
}
});
Which works fairly well, but it does preclude me from doing some things. For example, if I wanted to add another event, which was triggered by something from within my new dynamic view, I couldn't do that (since the events only look below the parent el
).
So an alternative might be to have a parent view, which knows about what element launches the dynamic element, and then creates/renders it.
velo.AppView = Backbone.View.extend({
el: "body",
events: {
"click a#dynamic-launcher": "launchDynamicView"
},
launchDynamicView: function(e){
e.preventDefault();
new MyDynamicView(); // Or something - Maybe I need to call render. Not sure.
}
});
Does this second technique make more sense?
Any guidance would be great!
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的解决方案是让
您的视图应该包含链接,而不是成为链接。
The easiest solution is to have
Your view should contain the link, not be the link.
您似乎没有按预期使用主干视图。您将事件绑定到#dynamic-launcher,但此元素不是定义此事件绑定的视图的一部分。您第二次尝试使用 AppView 效果更好。
当然,实现取决于您应用程序的目标,但也许您需要的是这样的东西:
初始起始 html 页面骨架:
应用程序视图
相应的应用程序模板
动态视图
相应的动态视图模板
You don't seem to be using backbone Views as intended. You're binding an event to a#dynamic-launcher, but this element is not part of the view in which this event binding is defined. Your second attempt with the AppView is better.
Of course, implementation depends on the goals of your app, but perhaps something like this is what you need:
An initial starting html page skeleton:
An App View
A corresponding AppTemplate
A Dynamic View
A Corresponding Dynamic View Template