以正确的方式获取主干回调

Backbone fetch callback the proper way

本文关键字:回调 获取 方式      更新时间:2023-09-26

我的主干应用程序有一个名为 schedule 的视图,我对成功和错误调用正确函数的区别有点困惑,我尝试了下面列出的两种可能的拖曳,但我没有什么是区别,从放置在外部视图中的路由器调用函数的正确方法是什么:

第一种方式:

        require([
            'app/collections/schedule',
            'app/views/schedule'
        ], function(ScheduleCollection, ScheduleView) {
           var scheduleCollection = new ScheduleCollection(),
            scheduleView = new ScheduleView({
                model: scheduleCollection
            });
            scheduleCollection.fetch({
                reset: true,                
                success: function(){
                    scheduleView.successHandler();
                },
                error: function(){
                    scheduleView.errorHandler()
                }
            });
        });

第二种方式

        require([
            'app/collections/schedule',
            'app/views/schedule'
        ], function(ScheduleCollection, ScheduleView) {
           var scheduleCollection = new ScheduleCollection(),
            scheduleView = new ScheduleView({
                model: scheduleCollection
            });
            scheduleCollection.fetch({
                reset: true,                
                success: scheduleView.successHandler(),
                error: scheduleView.errorHandler()                  
            });
        });

在计划视图中

successHandler: function(){
   console.log('success');
}

erroHandler: function(){
   console.log('error');
}

还有另一种选择:不是直接引用视图,而是提供集合作为相关视图的引用并侦听相关事件。例如,在相关视图中侦听集合的重置。如果这不是您要挂钩的事件,则从视图可以侦听的成功/错误回调触发自定义事件。

下面是处理重置的示例 - 扩展计划视图:

var ScheduleView = Backbone.View.extend({ 
    initialize: function () {
        this.listenTo(this.collection, 'reset', this.handleReset);
    },
    handleReset: function () {
        // do whatever you need to do here
    }
};
var scheduleCollection = new ScheduleCollection();
var scheduleView = new ScheduleView({ collection: scheduleCollection });

下面是与集合中的成功/错误处理程序绑定的自定义事件的示例:

var ScheduleCollection = Backbone.Collection.extend({
    getResults: function () {
        var self = this;
        this.fetch({
            reset: true,
            success: function (collection, response, options) {
                // you can pass additional options to the event you trigger here as well
                self.trigger('successOnFetch');
            },
            error: function (collection, response, options) {
                // you can pass additional options to the event you trigger here as well
                self.trigger('errorOnFetch');
            }
        });
    }
 };
var ScheduleView = Backbone.View.extend({
    initialize: function () {
        this.listenTo(this.collection, 'successOnFetch', this.handleSuccess);
        this.listenTo(this.collection, 'errorOnFetch', this.handleError);
    },
    handleSuccess: function (options) {
        // options will be any options you passed when triggering the custom event
    },
    handleError: function (options) {
        // options will be any options you passed when triggering the custom event
    }
};
var scheduleCollection = new ScheduleCollection();
var scheduleView = new ScheduleView({ collection: scheduleCollection });
scheduleCollection.getResults();

以这种方式连接的优点是可以删除集合对视图的依赖关系。如果您希望多个视图侦听集合(或集合模型)上发生的事件,并且是 Backbone 应用程序的更松散耦合的体系结构,则这一点尤其重要。

第一种方法是正确的,第二种是不正确的。 但这种方式是最简洁的:

scheduleCollection.fetch({
    reset: true,                
    success: scheduleView.successHandler,
    error: scheduleView.errorHandler
});

(虽然...从OP中,函数scheduleView.successHandler不存在,因此这可能是一个问题。

第二个不起作用的原因是您需要传递对函数的引用,而不是立即执行它。

var foo = myFunction(); // foo is set to myFunction's return value
var bar = myFunction; // bar is set to a REFERENCE to myFunction
foo === bar // FALSE
bar === myFunction // TRUE

更正的代码:

scheduleCollection.fetch({
    reset: true,                
    success: scheduleView.successHandler,
    error: scheduleView.errorHandler                  
});

现在,如果你想获得高级,在返回的XHR对象中使用jQuery promise API在各个方面都是优越的,并且不再需要回调。

scheduleCollection.fetch({ reset: true })
    .then(scheduleView.successHandler, scheduleView.errorHandler);

不同的是,你得到了一个可以传递的承诺......但这是另一篇文章的主题。 (无耻的插头)查看 adamterlson.com,了解我关于承诺的三部分系列......

你需要做的是将函数对象分配给"成功"和"错误",而不是函数的返回值。当您执行以下操作时:

function(){...}

它返回一个函数对象,因此success: function(){...}

是对的,但如果

a = function(){...}

你做a()它执行函数并返回返回值,因此 success: a()错了,但success: a是对的。