【发布时间】:2012-02-29 22:08:38
【问题描述】:
我正在尝试将我的所有主干.js 文件放在 javascript 匿名闭包中,以便我可以更好地构建我的代码并在将来集成 require.js。
这是我正在尝试做的一个示例(仅显示了 2 个文件,但我愿意为其余文件保留相同的结构):
main.js 之前:
Backbone.View.prototype.close = function () {
console.log('Closing view ' + this);
if (this.beforeClose) {
this.beforeClose();
}
this.remove();
this.unbind();
};
var AppRouter = Backbone.Router.extend({
initialize: function() {
$('#header').html( new HeaderView().render().el );
},
...etc etc
main.js AFTER(匿名关闭):
(function(AppRouter){
Backbone.View.prototype.close = function () {
console.log('Closing view ' + this);
if (this.beforeClose) {
this.beforeClose();
}
this.remove();
this.unbind();
};
//HERE, no way to instantiate AppRouter, won't work
var app = new AppRouter();
initialize: function() {
$('#header').html( new HeaderView().render().el );
},
...etc etc
})(app);
app-router.js 之前
var AppRouter = Backbone.Router.extend({
initialize: function() {
$('#header').html( new HeaderView().render().el );
},
...etc etc
app-router.js AFTER(匿名关闭)
(function(){
var AppRouter = Backbone.Router.extend({
initialize: function() {
$('#header').html( new HeaderView().render().el );
},
...etc etc
})(AppRouter);
所以 app-router.js 被包含在 main.js 之前,为什么我的 main.js 代码中的对象 AppRouter '未定义'?我无法实例化该对象。
【问题讨论】:
标签: javascript architecture backbone.js closures anonymous