如何在.on()事件监听器上使用.promise()?

时间:2014-01-31 15:41:12

标签: jquery

我有一个关于'fetch'事件的.on()监听器。是否有一种简单的方法可以在事件结束时触发事件?

      this.on('fetch', function() {
           log('fetch event started!!');
       });

       // fetch event ended???

我一直在玩.promise()但我没有取得好成绩。

更新 - 这是我的代码我正在使用集合的fetch事件,因此我可以显示/隐藏加载图标并执行其他工作。

   var tweetList = Backbone.Collection.extend({
            model: tweetModel,
            // used for collection.sort() 
            comparator: function (item) {
                return item.get("CreatedDate");
            },
            initialize: function(models, options) {
                this.on('fetch', function() {
                    console.log('fetch event started!!');

                });

            },
            fetch: function(options) {
                this.trigger('fetch', this, options);
                return Backbone.Collection.prototype.fetch.call(this, options);
            }
        });

我尝试将另一个事件绑定到fetch,但看起来它没有正确触发。

 var tweetList = Backbone.Collection.extend({
            model: tweetModel,
            // used for collection.sort() 
            comparator: function (item) {
                return item.get("SortOrder");
            },
            initialize: function(models, options) {
                this.on('fetch', function(m, o) {
                    log(o.status);

                });

            },
            fetch: function(options) {
                this.trigger('fetch', this, { status: "started"});
                this.trigger('fetch', this, { status: "ended"});
                return Backbone.Collection.prototype.fetch.call(this, options);
            }
        });

1 个答案:

答案 0 :(得分:1)

使用Q(https://github.com/kriskowal/q)和jQuery你可以做这样的事情......

this.on('fetch', function() {
           console.log('fetch event started!!');
        Q($.ajax(...)).then(function () {
            console.log("fetch event ended...");
        });
       });

或者,这是一个只使用jQuery的例子......

this.on('fetch', function() {
    console.log('fetch event started!!');
    $.when( $.ajax(...) ).then(function( data, textStatus, jqXHR ) {
        console.log('fetch event ended...');
    });
});