为什么我的backbone.Collection只有一个元素?(使用Require,TypeScript,Jasmine)

nxagd54h  于 2022-11-10  发布在  TypeScript
关注(0)|答案(1)|浏览(144)
  • 我是TypeScript和Jasmine的新手,对Backbone和Require也是新手,所以我还在尝试将一些片段粘合在一起。*

在一个TypeScript文件的Jasmine测试中,我试图定义一个backbone.Collection

(...)

class ModelA extends backbone.Model {
    idAttribute: "N";
    constructor(N: number, StringPropertyA: string, StringPropertyB: string, NumericPropertyA: number, NumericPropertyB: number, DatePropertyA: Date, DatePropertyB : Date) {
        super();
        this.attributes.N = N;
        this.attributes.StringPropertyA = StringPropertyA;
        this.attributes.StringPropertyB = StringPropertyB;
        this.attributes.NumericPropertyA = NumericPropertyA;
        this.attributes.NumericPropertyB = NumericPropertyB;
        this.attributes.DatePropertyA = DatePropertyA;
        this.attributes.DatePropertyB = DatePropertyB;
    }
}
            //var OldModelA = backbone.Model.extend({
            //    idAttribute: "N",
            //    constructor: function (N, PropertyA, PropertyB) {
            //        this.N = N;
            //        this.PropertyA = PropertyA;
            //        this.PropertyB = PropertyB;
            //    }
            //});

            var ModelACollection = backbone.Collection.extend({model: ModelA});

            var i = 1;
            var model1 = new ModelA(i++, "Abc", "dfD9"),
                model2 = new ModelA(i++, "Cde", "gdkl"),
                model3 = new ModelA(i++, "Cdy", "grger"),
                model4 = new ModelA(i++, "Zly", "dzeersds"),
                model5 = new ModelA(i++, "Zlz", "sdfsfz");

            var modelArray = [model1, model2, model3, model4, model5];

            var collection1 = new ModelACollection({ models: modelArray });
            var collection2 = new backbone.Collection({ models: modelArray });

(...)

我希望collection1.modelscollection2.models是5个元素的数组,但根据Chrome,它们的内容如下:
我想我错过了什么...

进一步搜索类似结果

var collection3 = new backbone.Collection();
        collection3.add(model1);
        collection3.add(model2);
        collection3.add(model3);
        collection3.add(model4);
        collection3.add(model5);
shyt4zoc

shyt4zoc1#

你的模型定义是罪魁祸首,它无可救药地混淆了 Backbone.js :

  • 它会遗漏父建构函式的呼叫以继承Backbone.Model属性http://backbonejs.org/#Model-constructor
  • 如果要直接写入属性,则必须将它们存储在attributes散列中,例如
this.attributes.N = N;
this.attributes.PropertyA = PropertyA;
this.attributes.PropertyB = PropertyB;

给定这些点,ModelA的一个可能的定义,用属性的哈希值调用父构造函数:

var ModelA = Backbone.Model.extend({
    idAttribute: "N",
    constructor: function (N, PropertyA, PropertyB) {
        Backbone.Model.call(this, {
            N: N,
            PropertyA: PropertyA,
            PropertyB: PropertyB
        });
    }
});

var m = new ModelA(1, "Abc", "dfD9");
console.log(m.toJSON());

请注意,如果您尚未覆写建构函式,则会以模型数组做为第一个参数来建立集合:

var collection1 = new ModelACollection(modelArray);

和演示
第一个

相关问题