backbone.js 未捕获的类型错误:此. model.toArray不是函数

mo49yndu  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(96)

我试图打印编辑和删除按钮的数据已添加。
产品型号:

var Food = Backbone.Model.extend({

    defaults: {
        fooddisplay: '',
        quantity: '',
        url: ''
    }

});

收藏:

var Foods = Backbone.Collection.extend({

});

/*var f1 = new Food({
    fooddisplay: 'bonay',
    quantity: 'poultry\'s',
    url: 'http://eggpoultry.com'
});

var f2 = new Food({
    type: 'manok',
    quantity: 'two manok\'s',
    url: 'http://heneralmanok.com'
});*/

var fs = new Foods();

查看方式:
更新:现在一切正常

var FoodView = Backbone.View.extend({
    model: new Food(),
    tagName: 'tr',
    initialize: function() {
        this.template = _.template($('.food-list-temp').html());
    },
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;

    }
});

var FoodsView = Backbone.View.extend({
    model: Foods,
    el: $('.food-list'),
    initialize: function() {
        this.model.on('add', this.render(), this);
    },
    render: function() {
        var self = this;
        this.$el.html('');
        this.model.each(function(food) {
            self.$el.append((new FoodView({model: food})).render().$el);
        });
        return this;
    }
});

var FoodsView = new FoodsView();

新增功能:

$(document).ready(function() {
    $('.add-food').on('click', function() {
        var f = new Food({
            fooddisplay: $('.fooddisplay-input').val(),
            quantity: $('.quantity-input').val(),
            url: $('.url-input').val()
        });
        console.log(f.toJSON());
        f.add(fs);
    });
});

问题是,它是这样说的。model.toArray不是一个函数。我不知道我在这里做错了什么。如果你回答世界上最伟大的程序员,提前感谢你。

jk9hmnmh

jk9hmnmh1#

this.model应该已经是数组,您不需要toArray

this.model.each(function(food) {
     self.$el.append((new FoodView({model: food})).render().$el);
  });

您需要执行以下操作以在集合更改时呈现视图

var FoodsView = Backbone.View.extend({
    model: Foods,
    el: $('.food-list'),
    initialize: function() {
        this.listenTo(this.model, 'add', this.render);
    },
   //......

相关问题