backbone 视图不适用于 this.model.toJSON()

backbone view not work with this.model.toJSON()

我已经在我的 backbone 代码上实现了一个视图,试图在我的模型上添加数据之前显示所有修改。但出于某种原因,我的观点 returns "this.model.toJSON() is not a function" 一直在尝试从我的表单中添加一些内容。我不明白怎么了。

它发生在视图 "userView" render() 内部。按照我的 2 个观点,模型和 collections.

型号:

      var userModel = Backbone.Model.extend({
          defaults: function() {
            return {
              nome: '',
              sobrenome: ''
            };
          }
      });

查看:

         var userView = Backbone.View.extend({
            model: new userModel(),
            tagName : 'div',
            initialize: function(){
              this.template = _.template($("#user-template").html());
            },
            render : function() {
               this.$el.html(this.template(this.model.toJSON()));
               return this;
            }
         });

视图 2:

        var userViewes = Backbone.View.extend({
            model: users,
            el: $("#user-container"),
            initialize: function(){
              this.model.on("add", this.render, this);
            },
            render: function() {
              var self = this;
              self.$el.html("");
              _.each(this.model.toArray(), function(user, i){
                self.$el.append((new userView({model:  userModel })).render().$el);
              });

              return this;
            }
         });

最后,我的 collection :

        var userCollections = Backbone.Collection.extend({
          model: userModel
        });

对于任何错误,我们深表歉意。

问题在于您将未初始化的模型传递给了视图。而不是 userModel,传递 user

_.each(this.model.toArray(), function(user, i){
    self.$el.append((new userView({model:  user })).render().$el);
});

另外,你不需要做this.model.toArray(),你可以这样做:

this.model.each(function(user, i){
    self.$el.append((new userView({model:  user })).render().$el);
});

Personally I'd call my collection collection and not model