如何将parameter passing给视图
我有一系列的button,点击时会显示一个位于button正下方的popup式菜单。 我想将button的位置传递给视图。 我怎样才能做到这一点?
ItemView = Backbone.View.extend({ tagName: 'li', events: { 'click': 'showMenu' }, initialize: function() { _.bindAll(this, 'render'); }, render: function() { return $(this.el).html(this.model.get('name')); }, showMenu: function() { var itemColl = new ItemColl(); new MenuView({collection: itemColl}); // how to pass the position of menu here? } });  当你构造MenuView时,你只需要传递额外的参数。 不需要添加initialize函数。 
 new MenuView({ collection: itemColl, position: this.getPosition() }) 
 然后,在MenuView ,可以使用this.options.position 。 
更新:由于@mu的状态太短 ,自1.1.0以来, Backbone Views不再自动附加传递给构造函数的选项this.options,但是如果你愿意,你可以自己做。
 所以在你的initialize方法中,你可以保存作为this.options传递的options : 
 initialize: function(options) { this.options = options; _.bindAll(this, 'render'); }, 
或者使用@Brave Dave描述的更精细的方法。
 添加一个选项参数来initialize : 
 initialize: function(options) { // Deal with default options and then look at options.pos // ... }, 
然后在创build视图时传入一些选项:
 var v = new ItemView({ pos: whatever_it_is}); 
有关更多信息: http : //backbonejs.org/#View-constructor
 从主干1.1.0开始, options参数不再自动附加到视图(参见问题2458的讨论)。 您现在需要手动附加每个视图的选项: 
 MenuView = Backbone.View.extend({ initialize: function(options) { _.extend(this, _.pick(options, "position", ...)); } }); new MenuView({ collection: itemColl, position: this.getPosition(), ... }); 
或者,您可以使用此迷你插件自动附加白名单选项,如下所示:
 MenuView = Backbone.View.extend({ options : ["position", ...] // options.position will be copied to this.position }); 
从其他地方通过
  new MenuView({ collection: itemColl, position: this.getPosition() }) 
添加一个选项参数来初始化查看你正在获取传递的variables,
 initialize: function(options) { // Deal with default options and then look at options.pos // ... }, 
获得价值的使用 –
  var v = new ItemView({ pos: this.options.positions}); 
使用this.options来检索观点
  // Place holder <div class="contentName"></div> var showNameView = Backbone.View.extend({ el:'.contentName', initialize: function(){ // Get name value by this.options.name this.render(this.options.name); }, render: function(name){ $('.contentName').html(name); } }); $(document).ready(function(){ // Passing name as argument to view var myName1 = new showNameView({name: 'Nishant'}); }); 
工作示例: http : //jsfiddle.net/Cpn3g/1771/