【问题标题】:How to trigger an Event after rendering Views with Backbone.js?使用 Backbone.js 渲染视图后如何触发事件?
【发布时间】:2012-01-19 19:02:32
【问题描述】:

我有很多使用模板的视图。视图渲染完美地工作,现在进入我的路由器,我正在寻找一种在所有视图渲染时触发事件的方法! 我使用了像 LAB.js 这样的 js 加载器,但没有任何效果!

完成所有渲染后,我将事件输入到 firebug 控制台,它就可以工作了!

如何以及在此处放置我的事件,以便在所有视图呈现时触发它!

**我的活动:**

$('div[id ^="solfg_"]').mobilyblocks();

**路由器:**

(function () {

 window.AppRouter = Backbone.Router.extend({
 routes: {
  ""  : "init"
 },

 init: function(){

   this.solfsmodel = new Solfs();
   this.solfsmodel.fetch(); 
   this.solfsView = new SolfsView({model: this.solfsmodel});

 }

});
var app_router = new AppRouter;
Backbone.history.start();
}(jQuery));

谢谢

更新: same problems

【问题讨论】:

    标签: javascript backbone.js backbone-events


    【解决方案1】:

    我发现解决方案只是使用 jquery 中的 $.when().then(),真是太神奇了,我从未见过这个 jquery 函数。

    *我的解决方案:*

    (function () {
    
     window.AppRouter = Backbone.Router.extend({
     routes: {
       ""  : "run"
     },
    
    initialize: function(){
      this.solfsmodel = new Solfs();
    
      this.solfsView = new SolfsView({model: this.solfsmodel});
    
    },
    run: function(){
      $.when(
         this.solfsmodel.fetch(); 
      ).then(function(){
         *$('div[id ^="solfg_"]').mobilyblocks();*
      });
    }
    });
    var app_router = new AppRouter;
    Backbone.history.start();
    }(jQuery));
    

    【讨论】:

    • 您是否将您的收藏绑定到视图?因为如果您只需要等待集合被提取,您可以使用事件successerror。我会写一个新的答案来告诉你怎么做。
    【解决方案2】:

    如果您只需要等待集合被提取,您可以使用fetch 方法的success 回调(来源:http://backbonejs.org/#Collection-fetch)。

    在使用其他库之前最好使用 Backbone.js 方法。

    所以你的代码应该是这样的:

    (function () {
    
        window.AppRouter = Backbone.Router.extend({
            routes: {
                ""  : "run"
            },
    
            initialize: function(){
                this.solfsmodel = new Solfs();
                this.solfsView = new SolfsView({model: this.solfsmodel});
            },
    
            run: function(){
                this.solfsmodel.fetch({
                    success: function () { 
                        $('div[id ^="solfg_"]').mobilyblocks();
                    }
                );
            }
        });
        var app_router = new AppRouter;
        Backbone.history.start();
    }(jQuery));
    

    【讨论】:

    • 如果你有多个模型,你怎么办?您是否为每次获取成功实施?
    • 确实,如果您提供多个模型,$.when 是一个更好的解决方案。但不要忘记检查是否发生错误。
    猜你喜欢
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2013-10-21
    • 2013-02-15
    相关资源
    最近更新 更多