我是否需要将2个模型传递到此视图中?

时间:2012-07-23 14:31:40

标签: javascript jquery backbone.js underscore.js

我有一个页面,显示每个由视图PhotoListItemView呈现的照片。单击照片后,会显示模式视图ModalAddToSetView,其中包含集SetListView列表。当点击其中一个SetView时,我需要将photo_idset_id发送到后端。

问题:在该论坛的点击处理程序中,我可以使用set_id轻松获取所点击的集this.model.get('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')
        })
    }
});

1 个答案:

答案 0 :(得分:0)

我没有看到将photo_id param传递给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')
    })
  }
});