简体   繁体   中英

Add values to a view with JSON and Backbone.js

I have a View (created using Backbone.View.extend) and a JSON object, I actually get the object from a couchdb database. How do I give the values to the view?

For example, I have these two objects:

var personJSON = {"name":"Buddy","email":"trout@fish.net"}
var personDetailsView; //Backbone.View

Is there a way to pass the values into the view without explicitly mapping them to the model?

I've found examples where you can add objects to a Backbone collections but not a view.

If you need to have access to the JSON object within the PersonDetailsView (Backbone.View) object, one way of doing this is to pass the JSON parameter as an option in the View's constructor:

//view definition
var PersonDetailsView = Backbone.View.extend({
  initialize: function(){
     this.person = this.options.person; //do something with the parameter
  }
});

var personJSON = {"name":"Buddy","email":"trout@fish.net"};
var personDetailsView = new PersonDetailsView({ person : personJSON });

From Backbone's official documentation:

When creating a new View, the options you pass are attached to the view as this.options , for future reference.

Usually, you retrieve model via model collection and pass it to view:

var person=personCollection.find(1);
var view=new PersonView({model: person});
var personView = Backbone.View.extend({
  template: JST['personTemplate'],
  render: function(){
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});
$('#container').html(personView.render().el);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM