【问题标题】:Backbone Collection Cant Find Model's View RenderBackbone Collection 找不到模型的视图渲染
【发布时间】:2012-12-23 12:39:11
【问题描述】:

我正在尝试渲染一个简单的集合视图,但遇到了一个奇怪的问题。

问题是当我尝试在集合视图中调用模型的渲染方法时,它找不到渲染方法。

我的模型和视图

var PersonModel = Backbone.Model.extend({});

var PersonView = Backbone.View.extend({
tagName : "person",
events:{
    "click h3":"alertStatus"

},
initialize:function(){
    this.model.on('change',this.render,this);

} ,
render:function(){

    var underscore_template = _.template('<h3>Name : <%= name %></h3>'+
        '<h3>Last Name : <%= surname %></h3>' +
        '<h3>Email : <%= email %> </h3>') ;

    console.log("Person View Render Oldu");
    this.$el.html(underscore_template(this.model.toJSON()));

},
alertStatus :function(e){
    alert("Clicked on Model View");
}
});

我的收藏和收藏视图

var PersonList = Backbone.Collection.extend({
model:PersonModel,
url:'/models'
});

var personList = new PersonList();

var PersonListView = Backbone.View.extend({
tagName : "personlist",
render : function(){
    this.collection.forEach(this.addOne,this);
},
addOne : function(personItem){
    var personView = new PersonView({model:personItem});
    this.$el.append(personView.render().el);  // The call to personView.render throws undefined
},
initialize : function(){
    this.collection.on('add',this.addOne,this);
    this.collection.on('reset',this.addAll,this);
},
addAll : function(){
    this.collection.forEach(this.addOne,this);
}
});

var personListView = new PersonListView({
collection:personList
});


personList.fetch({
success:function(){
    console.log("Fetch success");
}
});

我正在使用 Jquery 在文档上调用此 JS,并将其添加到 ID 为 app 的 div 中。

我的fetch也成功了。问题依然存在于Collection View的addOne函数尝试调用personView.render().el时

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript jquery dom backbone.js


    【解决方案1】:

    您忘记在渲染中返回元素:

    render : function() {
    
        var underscore_template = _.template('<h3>Name : <%= name %></h3>'+
            '<h3>Last Name : <%= surname %></h3>' +
            '<h3>Email : <%= email %> </h3>') ;
    
        console.log("Person View Render Oldu");
        this.$el.html(underscore_template(this.model.toJSON()));
    
        return this;  // chaining
    }
    

    否则无法链接,之后也无法访问el

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      相关资源
      最近更新 更多