如何将集合发送到另一个视图?

时间:2016-10-20 12:32:30

标签: javascript backbone.js

无论如何,如果没有listenTo方法将骨干集合发送到另一个视图,就像发送数组或其他东西一样发送它。

我在初始化函数中执行fetch,然后将集合放入我的数组中是不是很糟糕?

this.userModels = [];

this.collectionUser = new app.types.Users();
this.collectionUser.fetch();

this.userModels.push(this.collectionUser);

我试图像一个数组一样发送它,但有时我正在刷新我的网页

this.options child {
  length: 15,
  models: Array[15],
  _byId: Object,
  _listenId: "l4",
  _events: Object…
}

有时会得到零值

this.options child {
  length: 0,
  models: Array[0],
  _byId: Object,
  _listenId: "l4",
  _events: Object…
}

所以我想发送我的收藏而不用listenTo方法,如果可能的话。

第一个观点:

app.types.FirstView = Backbone.View.extend({

  initialize: function() {
    this.collectionUser = new app.types.Users();
    this.collectionUser.fetch();
  };

  sendCollection: function() {
    var secondView = new app.types.SecondView({
      collection: this.collectionUser
    });
  }
});

第二种观点:

app.types.SecondView = Backbone.View.extend({

  initialize: function(options) {
    this.collection = options.collection;

    // so i want to get this.collectionUser here without listenTo 
    // method and without fetch here is that possible ? I said
    // sometimes i get it sometimes not when i refersh my web page 
    // when i render it first time.
  };

});

1 个答案:

答案 0 :(得分:2)

Yes you can send everything with js and use initialize for that view. In your view you need to declare initialize function like this.

var someView = Backbone.View.extend({
    template: _.template('some html file'),
    initialize: function(options){
        this.collection = options.collection
    },
    events: {
        'click .someclass': 'doSomthing',
        'click #someId': 'doSomthingElse'
    },
    doSomthing: function(event){
         event.preventDefault();
         var that = this;
         that.collection.fetch({
            success: function(){
                that.$('element').append(that.collection);
            }
        });
    },
    render: function(){
        var that = this;
        that.$el.html(that.template);
        return this;
    }
});

And when u make new instance of your view need pass your collection as argument.

this.collectionUser = new app.types.Users();
this.view = new someView({collection: this.collectionUser});

This is it