Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

javascript - How to pass parameters to a view

I have a series of buttons which when clicked display a popup menu positioned just below the button. I want to pass the position of button to the view. How can I do that?

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?
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just need to pass the extra parameter when you construct the MenuView. No need to add the initialize function.

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

And then, in MenuView, you can use this.options.position.

UPDATE: As @mu is too short states, since 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.

So in your initialize method, you can save the options passed as this.options:

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

or use some finer ways as described by @Brave Dave.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...