如何将值从mainview传递到子视图Backbone.js

时间:2015-08-18 16:15:24

标签: javascript backbone.js

主视图

     events: {
    "click .open-sku-details":"openSkuDetails"

  },
  openSkuDetails: function(ev) {
    var self = this;
      var sku_id = $(ev.target).attr('sku_id');
      self.skuDetailsModel.set("id",sku_id);
      self.skuDetailsModel.fetch({
      }).done(function (response) {
      });

      this.skuDetails = new skuDetailsView({model:self.skuDetailsModel});
      return this.skuDetails.render();

  }

子视图

    var $ = jQuery = require('jquery'),
  Backbone = require('backbone'),
  Handlebars = require('handlebars'),
  _ = require('underscore'),
  skuDetailsTemplate = require("../../templates/product/SkuDetails.html"),
  skuDetailsModel = require('../../models/product/SkuDetailsModel');
var SkuDetailsView = Backbone.View.extend({
  el: ".sku-details-container",
  tagName:"div",

  initialize: function () {
    var self = this;
    this.skuDetailsModel = new skuDetailsModel();
    this.listenTo(self.skuDetailsModel, 'add', self.render);
    this.listenTo(self.skuDetailsModel, 'change', self.render);
     self.skuDetailsModel.fetch({
      }).done(function (response) {
      });
  },
  render: function () {
    var self = this;
    this.$el.html(skuDetailsTemplate({
      skuDetails: self.skuDetailsModel.toJSON(),
    }));
  }

});

module.exports = SkuDetailsView;

如何从一个视图传递id值另外两个?

1 个答案:

答案 0 :(得分:2)

通过the options argument传递。

在主视图中

this.skuDetails = new skuDetailsView({
    model:self.skuDetailsModel,
    sku_id: sku_id
});

在子视图中

initialize: function (options) {
    var sku_id = options.sku_id;
}

options对象仅在initialize函数中可用。如果在渲染时需要,请将其存储在this.sku_id = options.sku_id中。

当然,您也可以通过模型作为属性传递它,但如果它只是与视图相关,那么将它作为选项传递会更有意义。