Backbone.js:我在哪里设置jQuery?

Ric*_*ard 8 javascript backbone.js

我正在掌握Backbone.js,但有一件事我不明白是在哪里放置我需要设置页面的所有一次性jQuery代码.

你知道的事情:配置一个jQuery carousel插件,添加一个'滚动到顶部'箭头...当用户第一次加载页面时发生的一次性配置.

目前我正在我的路由器中执行此操作:

 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
 }
Run Code Online (Sandbox Code Playgroud)

Yeuch.我应该怎么做?应该initializeJqueryStuff是Router对象的另一个属性?它应该只是住在里面initialize吗?或者我应该将此代码与Backbone应用程序完全分开吗?

jev*_*lio 1

我通常定义一个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
    }
});
Run Code Online (Sandbox Code Playgroud)

用法:

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);
    }
});
Run Code Online (Sandbox Code Playgroud)