我有一系列按钮,当单击时显示一个弹出菜单,位于按钮下方。我想将按钮的位置传递到视图。我怎样才能做到这一点?

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开始 骨干视图不再自动将选项随附传递给构造函数。选项,但是如果您愿意,您可以自己做。

所以在你里面 initialize 方法,您可以保存 options 通过 this.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
    // ...
},

然后在创建视图时传递一些选项:

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()
})

添加一个选项参数以在视图中初始化您获取传递的变量,

initialize: function(options) {
   // Deal with default options and then look at options.pos
   // ...
},

获得价值使用 -

   var v = new ItemView({ pos: this.options.positions});

利用 这个 从视图中检索参数

 // 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/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top