Cómo pasar parámetros a una vista


Tengo una serie de botones que al hacer clic muestran un menú emergente situado justo debajo del botón. Quiero pasar la posición del botón a la vista. ¿Cómo puedo hacer eso?

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?
    }
});
Author: Emile Bergeron, 2011-10-18

5 answers

Solo necesita pasar el parámetro extra cuando construya el MenuView. No es necesario añadir la función initialize.

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

Y luego, en MenuView, puedes usar 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.opciones, pero puedes hacerlo tú mismo si lo prefieres.

Así que en su método initialize, puede guardar el options pasado como this.options:

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

O use algunas formas más finas como descrito por @Brave Dave.

 164
Author: dira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:02

Añade un argumento options a initialize:

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

Y luego pase algunas opciones cuando cree su vista:

var v = new ItemView({ pos: whatever_it_is});

Para más información: http://backbonejs.org/#View-constructor

 46
Author: mu is too short,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-30 17:56:55

A partir de backbone 1.1.0, el argumento options ya no se adjunta automáticamente a la vista (vea la edición 2458 para la discusión). Ahora necesita adjuntar las opciones de cada vista manualmente:

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

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

Alternativamente, puede usar este mini plugin para adjuntar automáticamente las opciones de la lista blanca, como así:

MenuView = Backbone.View.extend({
    options : ["position", ...] // options.position will be copied to this.position
});
 11
Author: Brave Dave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-09 21:52:40

Pase desde otra ubicación

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

Agregue un argumento de opciones para inicializar en view está obteniendo esa variable pasada,

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

Para obtener el valor use -

   var v = new ItemView({ pos: this.options.positions});
 -1
Author: Imtiaz Mirza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-30 15:04:05

Usa esto.opciones para recuperar argumentr en la vista

 // 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'});
    });

Ejemplo de trabajo: http://jsfiddle.net/Cpn3g/1771 /

 -2
Author: Nishant Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-28 13:54:06