javascript – 骨干提取回调正确的方法

前端之家收集整理的这篇文章主要介绍了javascript – 骨干提取回调正确的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的骨干应用程序有一个名为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',success: scheduleView.successHandler(),error: scheduleView.errorHandler()                  
            });
        });

在scheduleView中

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


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

解决方法

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

这是一个处理重置的示例 – 扩展您的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,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应用程序更松散的架构.

原文链接:https://www.f2er.com/js/151523.html

猜你在找的JavaScript相关文章