簡體   English   中英

Backbone.js集合視圖在控制台中正確格式化但在Dom中未顯示

[英]Backbone.js Collection View Properly Formatted in Console but Not Showing up in Dom

我正在解決我的第一個ribs.js問題,並且在使用集合時遇到了困難。 從控制台來看,問題似乎出在將收集視圖輸出到dom中。 收集數據在控制台中的格式正確,只是沒有顯示在瀏覽器中。 我不知道自己在做什么錯:

var RegisterModel = Backbone.Model.extend({
    urlRoot: 'api/process.php'
});

var RegisterView = Backbone.View.extend({
    el: "#register",
    template: _.template('<label for="<%= inputName %>"><%= label %></label><input name="<%= inputName %>" type="text" />'),
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});

var RegisterCollection = Backbone.Collection.extend({ 
    model: RegisterModel
});

var RegisterCollectionView = Backbone.View.extend({
    initialize: function(){
        this.collection.on('add', this.addOne, this);
        this.collection.on('reset', this.addAll, this);
    },  
    addOne: function(registerModel){
        var registerView = new RegisterView({model: registerModel});
        this.$el.append(registerView.render().el);  
    },
    addAll: function(){
        this.collection.forEach(this.addOne, this);
        this.$el.empty();   
    },
    render: function(){
        this.addAll();
        return this;
    }
});


var registerCollection = new RegisterCollection();
var todos = [{inputName: "first_name", label: "First Name"}, {inputName: "last_name", label: "Last Name"}];
registerCollection.reset(todos);


var registerCollectionView = new RegisterCollectionView({collection: registerCollection});
registerCollectionView.render();

這里:

addAll: function(){
    this.collection.forEach(this.addOne, this);
    this.$el.empty();   
},

渲染每個項目后,您將調用empty() 我假設您是說要交換這兩行。

addAll: function(){
    this.$el.empty();   
    this.collection.forEach(this.addOne, this);
},

還有這個:

el: "#register",

是錯的。 您有多個RegisterViews,因此在其上使用ID沒有意義。 同樣,這將使您的邏輯(而不是為視圖創建新元素)查找頁面中已經存在的元素。 您應該完全刪除該行。

您想要的是RegisterCollectionView上的el 現在,您沒有將該視圖附加到任何東西,因此它已呈現但不可見。

您應該能夠添加以下內容:

el: 'body'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM