2011-12-12 87 views
0

嗨,大家好我被困在从集合中显示的视图什么时候我想添加一些东西到模型按钮按zview显示新添加的人。下面是我的代码。如何在骨干中显示模型集合中的视图

$(document).ready(function(){ 

    var Person = Backbone.Model.extend({ 
     name: 'default name', 
     age: 100, 
     initialize: function(){ 
      this.bind('change', this.render, this); 
     } 
    }); 

    var PersonCollection = Backbone.Collection.extend({ 
     model: Person 
     }); 

    var PersonView = Backbone.View.extend({ 
     el: $('#personEL'), 

     events: 
     { 
      "click #login-btn" : "loginClick" 
     }, 
     loginClick: function() 
     { 
      var name = $('#name').val(); 
      var age = $('#age').val(); 
      var newPerson = new Person({name: name, age : age}); 


      this.personCollection.add(newPerson);   
      var showit = new zview(); 

     }, 
     initialize: function(){ 
     this.personCollection = new PersonCollection(); 

      this.render(); 
     }, 

     render: function() 
     { 
       var template = _.template($("#personInputTemplate").html(), {}); 
     this.el.html(template); 
     } 
    }); 



    zview = Backbone.View.extend({ 
     el: $('#personTable'), 

     initialize: function() 
     { 
     model: Person, 
     this.render(); 
     } 
     , 
     render: function() 
     { 
      var template = _.template($('#personDisplayTemplate').html(),this.Person.toJSON()); 
      console.log(template); 
      this.el.html(template); 
     } 
    }); 


var persons = new PersonView(); 

    }); 

HTML代码

<div id="display"> 
     <table id="personTable"> 

     </table> 
    </div> 


<script type="text/template" id="personInputTemplate"> 
    <p>Person Name<input type="text" id="name" /></p> 
    <p>Person Age<input type="text" id="age" /></p> 
    <p><button id="login-btn">Save</button></p> 
</script> 

<script type="text/template" id="personDisplayTemplate"> 
      <tr> 
       <td><span><%= name ? name : '' %></span></td> 
       <td><span><%= age ? age : '' %></span></td> 

      </tr> 
</script> 


<div id ="personEL"></div> 
<div id="showPerson"></div> 

语法和解释任何帮助apprecciated。感谢

+0

我注意到了两件事(抱歉,没有时间进一步分析):其一,你将模型的变化事件绑定到模型的渲染函数上?默认情况下,模型没有渲染 - 这是视图的用途。其次:在你的zview的渲染函数中,你引用this.Person.toJSON() - 人是你视图的模型,而不是视图上的变量。你会说this.model.toJSON。 – kinakuta

回答

1

除了看kinakuta的评论我建议看以下内容:

首先,你应该从zview删除以下代码,因为它是无效的JavaScript。

model: Person, 

然后,当您创建zview视图的实例可以传递一个模型作为参数,所以你可以替换

var showit = new zview(); 

有:渲染时

var showit = new zview({model: newPerson}); 

然后你的zview可以直接引用模型。

尝试更换:

var template = _.template($('#personDisplayTemplate').html(),this.Person.toJSON()); 

var template = _.template($('#personDisplayTemplate').html(), this.model.toJSON()); 

这至少应该让你开始在正确的轨道上。

+0

非常感谢冠军 –