javascriptjsonbackbone.jscouchdb

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.


Solution

  • 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.