简体   繁体   English

Backbone.js从它的initialize方法中获取集合

[英]Backbone.js fetch collection from it's initialize method

someone building an app for us, provided me the code so I could go through it, and I noticed this, which at first seems OK, and even nice to let the collection manage his data but after a while I started thinking about the possible pitfalls in this idea 有人为我们建立一个应用程序,为我提供了代码,所以我可以通过它,我注意到这一点,起初看起来还不错,甚至很高兴让收集管理他的数据,但过了一段时间我开始考虑可能的陷阱在这个想法

so: is it good practice to fetch a collection's data from it's own initialize method. 所以:从它自己的初始化方法中获取集合的数据是一种好习惯。

for example: 例如:

var Book = Backbone.Model.extend({});

var Books = Backbone.Collection.extend({

    url: '/books',

    initialize: function(){
        // do some logic here

        // if collection is empty, fetch from server
        if(this.size() == 0)
            this.fetch();
    }

});

i ask this because i feel it might be a problem in the following situation: 我问这个是因为我认为在下列情况下可能会出现问题:

suppose we are in a routeAction: 假设我们在routeAction中:

books: function() {
    var books = new Books();
    var bookList = new BookList({ collection: books });
}

isn't this situation possible failure, if the fetch would be faster than the initialization of the view, where the view would have bound to a reset event, the reset would have triggered way before the initialize of the view had been executed? 是不是这种情况可能失败,如果获取速度比视图初始化速度快,视图会绑定到重置事件,重置会在视图初始化执行之前触发?

am I wrong on this, or should I submit a ticket to get this fixed. 我错了,或者我应该提交一张票来解决这个问题。

While in practice the initialization of the view will most likely occur before fetch() is complete (and you would bind render() to reset not initialize() ) it's a really bad idea to rely on the order of async operations anyway. 虽然实际上视图的初始化很可能在fetch()完成之前发生(并且你将render()绑定到reset而不是initialize() )但是依赖于异步操作的顺序是一个非常糟糕的主意。 In other words, your code should be written in a way that makes order irrelevant. 换句话说,您的代码应该以使订单无关的方式编写。

I have seen fetch() being called in initialize() in various projects. 我在各种项目中看到了在initialize()中调用fetch() I still think it's undesirable and bad practice. 我仍然认为这是不可取的和不好的做法。 Explicitly fetching when you need to also has these advantages: 当您需要时也明确获取这些优点:

  1. You can do it when you need to, not every time you create a new collection. 您可以在需要时执行此操作,而不是每次创建新集合时都可以执行此操作。
  2. You can do certain things in order if you want to: 如果您想要,您可以按顺序执行某些操作:

    For example, you can initialize your view and render only once you have fetched. 例如,您可以初始化视图并仅在获取后进行渲染。

     var bookList, books = new Books(); var p = books.fetch(); p.done(function () { bookList = new BookList({collection: books }); bookList.render(); }); 
  3. It makes testing easier. 它使测试更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM