Backbone extiende un modelo antes de convertirlo en una plantilla

I would like to pass additional variables to my template, i.e. some that are not contained within a model. These are basically display parameters like how the screen will appear to the user next. It doesn't have to be saved in the database.

Intenté esto pero no parece funcionar:

render: function () {
         this.extra_list = _.shuffle(this.extra_list);
         jQuery.extend(this.model, this.extra_list);
         this.$el.html(this.template(this.model.toJSON()));..
         return this;
      }

When I make a reference to extra_list in the template I get an error that the variable is not defined. What am I missing?

preguntado el 10 de septiembre de 13 a las 00:09

1 Respuestas

model.toJSON() returns a model's atributos not properties. Since your extend function is adding those properties directly to the model, they are undefined when you pass the output of toJSON a su plantilla.

O agregue extra_list to your model's attributes (which it sounds like you do not want to do), or combine the output of toJSON con extra_list and pass that to your template.

Edit: As noted in the comments, you can use _.extend to "merge" extra_list with your model's attributes:

  render: function () {
    this.extra_list = _.shuffle(this.extra_list); 

    var data = _.extend(this.model.toJSON(), this.extra_list);

    this.$el.html(this.template(data));
    return this;
  }

Respondido el 10 de Septiembre de 13 a las 04:09

OK, what's the best way to combine them? Do I simply write this.template(jQuery.extend(this.model.toJSON(), this.extra_list)? - user1813867

@user1813867: I'd _.extend(this.model.toJSON(), this.extra_list), el valor por defecto toJSON returns a copy of the model's attributes para que no tengas que preocuparte por _.extend overwriting anything private. You could use $.extend en lugar de _.extend si querías. - mu es demasiado corto

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.