javascript Backbone fetch 回调的正确方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19713613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:34:25  来源:igfitidea点击:

Backbone fetch callback the proper way

javascriptbackbone.jsamd

提问by ahmedsaber111

My Backbone application has a view called schedule, I am a bit confused about the difference of calling the proper function on success and error, I am tried the both of tow possible listed below but i didn't what is difference and what is the right way to call a function from router placed in outside view:

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

The first way:

第一种方式:

        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()
                }
            });
        });

The second way

第二种方式

        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()                  
            });
        });

in the scheduleView

在 scheduleView

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


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

回答by kinakuta

There's another option: rather than referencing the views directly, provide the collection as a reference to the concerned views and listen for relevant events. For example, listen for reset on the collection in the concerned view. If that's not the event you want to hook into, then trigger a custom event from the success/error callbacks that your view can listen to.

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

Here's an example handling reset - extend your ScheduleView:

这是一个处理重置的示例 - 扩展您的 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 });

here's an example of custom events tied to the success/error handlers from the collection:

这是与集合中的成功/错误处理程序相关联的自定义事件示例:

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();

The advantage of wiring up this way is you remove the dependency the collection has on the view. This is especially key if you want more than one view to listen for events happening on your collection (or you collection models) and is a more loosely coupled architecture for your Backbone application.

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

回答by McGarnagle

The first way is correct, the second is incorrect. But this way would be most concise:

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

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

(Although ... from the OP, the function scheduleView.successHandlerdoes not exist, so that could be a problem.)

(虽然......从OP来看,该功能scheduleView.successHandler不存在,所以这可能是一个问题。)

回答by Adam Terlson

The reason your second one doesn't work is that you need to pass a reference to a functionrather than executing it immediately.

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

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

Corrected code:

更正的代码:

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

Now, if you want to get advanced, using the jQuery promise APIoff of the returned XHR object is superior in every way and callbacks should never be necessary anymore.

现在,如果您想更进一步,使用返回的 XHR 对象的jQuery promise API在各方面都更胜一筹,并且不再需要回调。

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

The difference is that you get a promise back that can be passed on... but that's a topic for a different post. (Shameless plug) Check out adamterlson.comfor my three-part series on promises....

不同之处在于你得到了一个可以传递的承诺......但这是另一个帖子的主题。(无耻的插件)查看adamterlson.com以了解我关于承诺的三部分系列......

回答by 2292amit

What you need to do is assign function object to 'success' and 'error' and not the return value of function. When you do:

您需要做的是将函数对象分配给“成功”和“错误”,而不是函数的返回值。当你这样做时:

function(){...}

it returns a function object and hence success: function(){...}

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

is right but if

是对的,但如果

a = function(){...}

and you do a()it executes the function and returns the return value and hence success: a()is wrong but success: ais right.

并且您a()执行该函数并返回返回值,因此 success: a()是错误的但是success: a是正确的。