Backbone以正确的方式获取回调

时间:2013-10-31 18:02:34

标签: javascript backbone.js amd

我的Backbone应用程序有一个名为 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()                  
            });
        });
scheduleView

中的

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


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

4 个答案:

答案 0 :(得分:16)

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

以下是处理重置的示例 - 扩展ScheduleView:

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应用程序的松散耦合架构,这一点尤为关键。

答案 1 :(得分:5)

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

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

(虽然......来自OP,函数scheduleView.successHandler不存在,所以这可能是个问题。)

答案 2 :(得分:2)

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

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我的三部分关于承诺的系列....

答案 3 :(得分:0)

您需要做的是将函数对象分配给'success'和'error',而不是函数的返回值。 当你这样做时:

function(){...}

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

是对的但是如果

a = function(){...}

并执行a()它执行函数并返回返回值 success: a()错误,但success: a是对的。