我需要将2个模型传递到此视图中吗

Do I need to pass 2 Models into this View?

本文关键字:视图 2个 模型      更新时间:2024-01-03

我有一个页面,其中显示了View PhotoListItemView渲染的多张照片。单击照片时,会出现模式视图ModalAddToSetView,其中包含集合SetListView的列表。当单击其中一个Set SetView时,我需要将photo_idset_id发送到后端。

问题:在Set的点击处理程序中,我可以使用this.model.get('id')轻松获得点击的集合的set_id。获取photo_id的常规方式是什么?

照片视图

photo_id在传递到此视图的模型中

PhotoListItemView = Backbone.View.extend({
    events: {
        'click #add.photo_btn' : 'add'
    },
    add: function(event) {
        event.stopImmediatePropagation();
        // Show modal
        $('#modal_addit').modal();
        modalAddToSetView = new ModalAddToSetView({ model: this.model });
    }
});

模态视图

ModalAddToSetView = Backbone.View.extend({
    initialize: function() {
        this.render();
        this.renderSets();
    },
    render: function() {
        $(this.el).html( this.template( this.model.toJSON() ) );
        return this;
    },
    renderSets: function() {
        this.setList = new SetCollection();
        this.setListView = new SetListView({ collection: this.setList });
        this.setList.fetch({
            data: {user_id: $('#user_id').val()},
            processData: true
        });
    }
});

集合视图

SetListView = Backbone.View.extend({
    initialize: function() {
        this.collection.on('reset', this.render, this);
    },
    render: function() {
        this.collection.each(function(set, index) {
            $(this.el).append( new SetView({ model: set }).render().el );
        }, this);
    }
});
SetView = Backbone.View.extend({
    template: _.template( $('#tpl_modal_addit_set').html() ),
    events: {
        'click': 'addToSet'
    }
    render: function() {
        $(this.el).html( this.template( this.model.toJSON() ) );
        return this;
    },
    addToSet: function() {
        $.post('api/add_to_set', {
            photo_id: ,         // HOW DO I PASS THE PHOTO_ID?
            set_id: this.model.get('id')
        })
    }
});

我认为将photo_id参数传递到SetListView构造函数并再次传递给SetView构造函数没有任何问题:

// code simplified and no tested
SetListView = Backbone.View.extend({
  initialize: function( opts ) {
    this.photo_id = opts.photo_id;
    this.collection.on('reset', this.render, this);
  },
  render: function() {
    this.collection.each(function(set, index) {
      $(this.el).append( new SetView({ model: set, photo_id: this.photo_id }).render().el );
    }, this);
  }
});
SetView = Backbone.View.extend({
  initialize: function( opts ) {
    this.photo_id = opts.photo_id;
  },
  addToSet: function() {
    $.post('api/add_to_set', {
      photo_id: this.photo_id,
      set_id: this.model.get('id')
    })
  }
});