2013-02-17 73 views
2
$('button').click(function(){ 
    App.vent.trigger("box:change"); 
}); 

App.BoxView = Backbone.View.extend({ 
    initialize: function(options) { 

    this.listenTo(App.vent, "box:change", this.alter); // animate, etc. 
    }, 

    ... 

}); 

我有一個主視圖,在至極我希望做一些改變的時候(和/或):backbone.js在事件(發泄)完成時做些什麼?

  1. 該事件由我所有的箱子
  2. 我所有的箱子一些動畫做加工

不能換我解決這個(長時間的工作日內)頭...... 請幫助=) 什麼是更好的做法?

我正在尋找這樣的事情:

App.MainView = Backbone.View.extend({ 
     initialize: function(options) { 

     // when all the events are complete 
     this.listenTo(App.vent, "box:change").onComplete(this.rearrange_stuff); 

     // when all the animations are complete 
     this.listenTo(App.animationBuffer, "box:fadeOut").onComplete(this.rearrange_stuff); 

     }, 

     ... 

}); 

更新: 什麼,如果我有事件的長鏈 - 完成 - 活動 - 在我的應用程序完成(不循環),什麼是更好的方法來設置這個隊列?

+0

你的'App.vent.trigger()'調用是單線程的,所以當'trigger'返回時所有的處理程序都會返回。動畫是所有工作的地方。 – 2013-02-18 01:49:58

+0

@ muistooshort是的,我可以以某種方式收集動畫並使用諾言爲所有動畫完成時設置回調。但是這也意味着我需要在我的alter()中只有動畫(或setTimeouts)... – Hontoni 2013-02-18 17:56:18

+0

你知道有多少盒子嗎?在動畫結束時,您可以讓每個盒子觸發一個「我已經完成了我正在做的所有事情」事件。然後,當你調用'trigger'的時候,如果你知道有多少個盒子('n'),你可以列出這些定製事件,並在你收到'n'時做任何需要做的事情。 – 2013-02-18 18:59:18

回答

0

使用jQuery我發現的承諾,只需要計算出如何應用此我所有的意見..

http://api.jquery.com/promise/

(更新)

現在,我已經做到了這樣... http://jsfiddle.net/Antonimo/YyxQ3/2/

App.vent = _.extend(Backbone.Events, { 
    promise: function(name){ 
     if(typeof this._bills[name] === "undefined"){ 
      this._bills[name] = 0; 
     } else { 
      this._bills[name] ++; 
     } 
    }, 
    keepPromise: function(name){ 
     var that = this; 
     setTimeout(function(){ 
      if(typeof that._checks[name] === "undefined"){ 
       that._checks[name] = 0; 
      } else { 
       that._checks[name] ++; 
      } 
      if(typeof that._bills[name] !== "undefined"){      
       if(that._checks[name] >= that._bills[name]){ 
        that._checks[name] = 0; // reset 
        that._bills[name] = 0; // reset 
        that.trigger(name); // emit event 
       } 
      } 

     }, 30); 
    }, 
    _bills: {}, 
    _checks: {} 
}); 

// usage: 

alter: function() { 
     App.vent.promise('some:event'); 
     // Animate, or not.. 
     App.vent.pay('some:event'); 
}, 
0

我一直在尋找解決這一發現這個插件骨幹,增加了一個「TR iggerThen「方法應用於Backbone.Events和其他Backbone對象,這些對象允許您觸發事件並在所有事件偵聽器完成後調用函數。

https://github.com/bookshelf/trigger-then

如果有一個正式的骨幹解決方案,這雖然在整個Backbone.Events框架中使用的承諾這將是很好。

相關問題