我需要创建一个基本 View ,我的所有 View 都会扩展。 我不太确定何时何地声明此 View 。
基本上,我需要将全局变量
注入(inject)到我的所有模板中,但我不会在每个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
};
});
现在我所有的 View 都继承自 Backbone.View
,如下所示:
App.View.Dashboard = Backbone.View.extend({
我想创建自己的基本 View
,应用程序中的所有 View 都将扩展它。
这是我到目前为止所做的,但我不知道在哪里放置这段代码,因为在 app.js 中我正在加载仪表板 View ,所以我需要之前这样做,但我需要需要这个基本 View 所有 View 中的对象...所以我迷路了:(
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
谢谢,马克西姆。
最佳答案
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()
}
});
关于backbone.js - 如何在backbone.js中创建基本 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12260264/