Pregunta

Tengo una serie de botones que cuando hace clic en Muestra un menú emergente colocado 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?
    }
});
¿Fue útil?

Solución

Solo necesita pasar el parámetro adicional cuando construye el Menuview. No hay necesidad de agregar el initialize función.

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

Y luego, en MenuView, puedes usar this.options.position.

ACTUALIZAR: Como @mu son estados demasiado cortos, desde 1.1.0, Las vistas de la red troncal ya no adjuntan automáticamente opciones que se pasan al constructor como esta. Opciones, pero puede hacerlo usted mismo si lo prefiere.

Entonces en tu initialize Método, 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.

Otros consejos

Agregue un argumento de opciones 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

A partir de la columna vertebral 1.1.0, el options el argumento es ya no adjunto automáticamente a la vista (ver Problema 2458 Para 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, puedes usar este mini complemento Para atacar automáticamente opciones de lista blanca, como así:

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

pasar de otra ubicación

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

Agregue un argumento de opciones para inicializar en la vista que está obteniendo esa variable aprobada,

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

Para obtener el uso de valor -

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

Usar esto. Opciones Para recuperar el argumento a 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/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top