简体   繁体   English

使用JSON和Backbone.js向视图添加值

[英]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. 我有一个View(使用Backbone.View.extend创建)和一个JSON对象,实际上我是从沙发数据库中获取该对象的。 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. 我找到了一些示例,您可以在其中添加对象到Backbone集合中,但不能在视图中添加对象。

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: 如果您需要访问PersonDetailsView(Backbone.View)对象中的JSON对象,执行此操作的一种方法是将JSON参数作为选项传递给View的构造函数:

//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: 从Backbone的官方文档中:

When creating a new View, the options you pass are attached to the view as this.options , for future reference. 创建新视图时,您传递的选项将作为this.options附加到视图中,以供将来参考。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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