【问题标题】:How to create a base view in backbone.js?如何在backbone.js 中创建基本视图?
【发布时间】:2012-08-28 22:09:14
【问题描述】:

我需要创建一个基本视图,我的所有视图都会扩展。 我不确定在何时何地声明此视图。

基本上,我需要将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 中我正在加载仪表板视图,所以我需要先做,但我需要这个基本视图所有视图中的对象......所以我迷路了:(

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

谢谢,马克西姆。

【问题讨论】:

    标签: backbone.js extends backbone-views


    【解决方案1】:
    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()
      }
    });
    

    【讨论】:

    • 我最终以另一种方式做到了,但这个答案看起来是我的问题的最佳答案;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多