[英]Backbone.js: Where do I put my jQuery setup?
我正与Backbone.js交手,但我不明白的一件事是,将放置页面所需的所有一次性jQuery代码放在哪里。
您知道这种事情:配置jQuery轮播插件,添加“滚动到顶部”箭头...用户首次加载页面时发生的一次性配置。
目前,我正在路由器中执行此操作:
var AppRouter = Backbone.Router.extend({
routes: {
// some routes
},
initialize: function() {
initializeJqueryStuff();
} ...
});
var StateApp = new AppRouter();
Backbone.history.start({
pushState: true
});
function initializeJqueryStuff() {
// one-off jQuery stuff goes here
}
嗯 我应该怎么做? initializeJqueryStuff
应该是Router对象的另一个属性吗? 是否应该将所有内容都保存在initialize
? 还是我实际上应该将此代码与Backbone应用程序完全分开?
我通常定义一个LayoutView
,即一个根视图,它负责呈现应用程序中的所有“实际”视图。 在需要运行任何其他视图代码之前,此布局视图仅初始化一次。 这也是我倾向于进行一次性视图配置的地方。
样品:
//LayoutView should be considered a singleton, only initialized once
var LayoutView = Backbone.View.extend({
el:'body',
initialize: function() {
this.initializeSomejQueryStuff();
},
renderChild: function(child) {
if(this._currentChild)
this._currentChild.remove();
this._currentChild = child;
this.$el.html(child.render().el);
},
initializeSomejQueryStuff: function() {
//init here
}
});
用法:
var AppRouter = Backbone.Router.extend({
routes: {
"foo/:id": "foo"
},
initialize: function() {
this.layout = new LayoutView();
},
foo: function(id) {
var model = new Foo({id:id});
var view = new FooView({model:model});
//delegate the view rendering to a layout
this.layout.renderChild(view);
}
});
嗯...对不起,如果我英语不好的话我错过了一些细节。 但是,正如我所看到的,您的问题的重点是:您可以在哪里配置和放置与Backbone不相关的jQuery内容? 总之,您可以分隔此代码,然后将其链接到.html中
骨干只是一点MVC。 您可以在Backbone.View.extend({...})
操纵渲染器的功能以及与视图相关的一些js东西,但是总的来说,我认为为不同的东西制作不同的结构是个好主意。 像这样:
.../
public/
css/
img/
lib/
..any source code for your plugins..
tpl/
..for your templates..
js/
models/
models.js
views/
..your views.js..
main.js(your backbone router and for example, .loadTemplate() func for templates and other)
..any code for plugings configuration..
因此,正如我认为的那样,该结构可以帮助您理解什么是源代码,并使您的编码清晰明了。
希望对您有帮助。 对不起,我误会了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.