如何将参数传递给视图

时间:2011-10-18 06:13:31

标签: javascript backbone.js

我有一系列按钮,点击后会在按钮下方显示一个弹出菜单。我想将按钮的位置传递给视图。我怎么能这样做?

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?
    }
});

5 个答案:

答案 0 :(得分:166)

构建MenuView时,只需传递额外参数即可。无需添加initialize函数。

new MenuView({
  collection: itemColl,
  position: this.getPosition()
})

然后,在MenuView中,您可以使用this.options.position

更新@mu is too short states,自1.1.0起,Backbone Views no longer automatically attach options passed to the constructor as this.options, but you can do it yourself if you prefer.

因此,在initialize方法中,您可以将options保存为this.options

initialize: function(options) {
    this.options = options;
    _.bindAll(this, 'render');
},

或使用更精细的方式described by @Brave Dave

答案 1 :(得分:46)

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

答案 2 :(得分:12)

从主干1.1.0开始,options参数自动no longer attached到视图(请参阅issue 2458进行讨论)。您现在需要手动附加每个视图的选项:

MenuView = Backbone.View.extend({
    initialize: function(options) {
        _.extend(this, _.pick(options, "position", ...));
    }
});

new MenuView({
    collection: itemColl,
    position: this.getPosition(),
    ...
});

或者,您可以使用this mini plugin自动附加白名单选项,如下所示:

MenuView = Backbone.View.extend({
    options : ["position", ...] // options.position will be copied to this.position
});

答案 3 :(得分:-1)

从其他地方传递

 new MenuView({
   collection: itemColl,
   position: this.getPosition()
})

添加一个options参数,以便在视图中初始化你正在获取传递的变量

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

获取价值 使用 -

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

答案 4 :(得分:-2)

使用 this.options 检索视图中的argumentr

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