How to create a base view in backbone.js?

纵饮孤独 提交于 2019-12-03 06:16:48

问题


I need to create a base view which all my views would extends. I'm not really sure where and when to declare this view.

Basically, I need to inject global variables to all my templates and I don't do to that in each and every render() methods.

this is my tree structure for now:

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

this is my 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
    };
});

And for now all my view inherit from Backbone.View like this:

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

I want to create my own Base View which all the views from the application would extends. This is what I've done so far, but I don't know where to place this piece of code because in app.js I'm loading the Dashboard view so I need to do it before but I need to require this base view object in all views... so I'm lost :(

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);
        }
    });

});

Any idea or remarks are welcome. An answer would be the best :D

Thanks, Maxime.


回答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()
  }
});


来源:https://stackoverflow.com/questions/12260264/how-to-create-a-base-view-in-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!