Ampersand.js中同一类的多个子视图

Multiple subviews of the same class in Ampersand.js

本文关键字:一类 视图 js Ampersand      更新时间:2023-09-26

我正在尝试将多个子视图添加到Ampersand.js中的视图中,其中这些子视图的类型相同。然而,Ampersand似乎只允许我拥有一个类类型的对象,并且声明第二个对象会覆盖第一个对象的所有属性。例如:

var chart1 = new PieChart('userChart');
var chart2 = new PieChart('deviceChart');
module.exports = PageView.extend({
  pageTitle: 'Home',
  template: require('../../../templates/pages/home.hbs'),
  render: function() {
    this.renderWithTemplate();
    this.renderSubview(chart1, document.getElementById('userChart'));
    this.renderSubview(chart2, document.getElementById('deviceChart'));
  }
});

将只呈现第二个图表,但是如果我注释掉第二个,第一个图表将显示良好。在检查对象时,两者都将'deviceChart'作为参数。我尝试过创建一个名为PieChart2的全新类,这消除了问题,但为我可能想要显示的每种类型的图表创建一个全新的类将是荒谬的。

有什么想法吗?

我认为您的PieChart有问题。我试着重现你的问题,一切都很好,正如预期的那样。这是我的工作代码:

var OneView = View.extend({//analogous to your PieChart
  template: '<b></b>',
  props: {
    type: 'string'
  },
  bindings: {
    'type': 'b'
  },
  initialize: function(type){
    this.type = type;
  }
});
var view1 = new OneView('view1');
var view2 = new OneView('view2');
module.exports = View.extend({
  template: '<div><div id="view1"></div><div id="view2"></div></div>',
  autoRender: true,
  render: function(){
    this.renderWithTemplate(this);
    this.renderSubview(view1, document.getElementById('view1'));
    this.renderSubview(view2, document.getElementById('view2'));
    return this;
  }
});

顺便说一下,您应该在render函数内部实例化您的视图。否则,每次调用render()时它们都是一样的(因为CommonJS模块的工作方式),而且很可能不是您想要的。此外,要查询视图中的元素,可以使用this.querySelector('SELECTOR')而不是document.getElementById