【问题标题】:Putting Backbone.js in javascript anonymous closures将 Backbone.js 放入 javascript 匿名闭包中
【发布时间】:2012-02-29 22:08:38
【问题描述】:

我正在尝试将我的所有主干.js 文件放在 javascript 匿名闭包中,以便我可以更好地构建我的代码并在将来集成 require.js。

这是我正在尝试做的一个示例(仅显示了 2 个文件,但我愿意为其余文件保留相同的结构):

ma​​in.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

ma​​in.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


    【解决方案1】:

    app 变量在 main.js 中的函数内部定义,并被传递给它不可用的相同函数。

    (function(AppRouter){ .....
    
    var app = new AppRouter();
    
    ....}(app)
    

    调用函数时需要传递AppRouter

    (function(AppRouter){ .....
    
    var app = new AppRouter();
    
    ....}(AppRouter)
    

    另外,根据 app-router,AppRouter 在全局上下文中不可用,因此您需要像 follow 这样返回扩展对象,然后它将可以在整个应用程序中访问

    var AppRouter = (function(){
    return Backbone.Router.extend({
    
    initialize: function() {
        $('#header').html( new HeaderView().render().el );
    },
    ...etc etc
    })();
    

    【讨论】:

      猜你喜欢
      • 2013-04-08
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多