backbone.js在事件(发泄)完成时做了什么?

时间:2013-02-17 19:29:29

标签: javascript jquery events backbone.js

$('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.
  },

  ...

});

我有一个主视图,我希望在(和/或)时做一些更改:

  1. 该事件由我的所有方框处理
  2. 我的所有盒子都完成了一些动画
  3. 无法绕过这个(长时间工作)... 请帮助=) 什么是更好的做法?

    我正在寻找类似的东西:

    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 );
    
          },
    
          ...
    
    });
    

    更新:   如果我在我的应用程序中有一长串事件 - 完成 - 事件 - 完成(不是循环),那么设置此队列的更好方法是什么?

2 个答案:

答案 0 :(得分: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');
},

答案 1 :(得分:0)

我正在寻找一个解决方案,并发现Backbone的这个插件为Backbone.Events和其他Backbone对象添加了一个“triggerThen”方法,它允许你触发一个事件然后在所有事件监听器之后调用一个函数已经完成了。

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

如果有一个官方的Backbone解决方案,虽然在整个Backbone.Events框架中使用了promises,但这将是很好的。

相关问题