如何在backbone.js中创建基本视图?

时间:2012-09-04 09:14:37

标签: backbone.js extends backbone-views

我需要创建一个基本视图,我的所有视图都会扩展。 我不确定在何时何地宣布这种观点。

基本上,我需要将global variables注入我的所有模板中,而不是在每个render()方法中都这样做。

现在这是我的树结构:

|-main.js
|-app.js
|-require.js
|-App
|  |-View
|  |   |-Dashboard.js
|  |   |-Header.js
|  |   |-Content.js
|  |-Model
|  |-Collection
|  |-Template
|
|-Libs
   |-...

这是我的app.js

var App = {
    ApiURL: "http://domain.local",
    View: {},
    Model: {},
    Collection: {},
    Registry: {},
    Router: null
};

define(['backbone', 'View/Dashboard'], function(Backbone){
    var AppRouter = Backbone.Router.extend({
        routes : {
            "dashboard": "index",
        },

        index: function() {
            console.log('routing index route...');
            var x = new App.View.Dashboard({el:$('#main-content'), type:'other'});
        }
    });

    var initialize = function() {
        App.Router = new AppRouter;
        Backbone.history.start({pushState: true});
        console.log('Backbone is running...');
    };

    return {
        initialize : initialize
    };
});

现在,我的所有观点都继承自Backbone.View

App.View.Dashboard = Backbone.View.extend({

我想创建自己的Base View,其中应用程序的所有视图都会扩展。 这是我到目前为止所做的,但我不知道在哪里放置这段代码,因为在app.js中我正在加载Dashboard视图所以我需要先做它但我需要这个基本视图所有观点中的对象......所以我迷失了:(

define(['backbone', 'underscore', 'twig'], function(Backbone, _){

    App.View.Base = Backbone.View.extend({});
    _.extends(App.View.Base.prototype, {
        initialize: function(params)
        {
            this.el = params.el;
            this.init(params);
        },

        init: function(params)
        {
        },

        renderTemplate:function(template_path, data)
        {
            var tpl = twig({href:template_path, async:false});

            // Inject variables
            data.user = App.Registry.User;
            data.account = App.Registry.Account;

            return tpl.render(data);
        }
    });

});

欢迎任何想法或评论。答案是最好的:D

谢谢,Maxime。

1 个答案:

答案 0 :(得分:11)

App.View.Base = Backbone.View.extend({
  baseMethod: function( params ) {};
});

App.ExtendedView.Base = App.View.Base.extend({
  // new stuff here

  // overriding App.View.Base.baseMethod
  baseMethod: function( params ) {
    // overriding stuff here 
    App.View.Base.prototype.baseMethod.call(this, params); // calling super.baseMethod()
  }
});