Collection.get返回undefined Backbone.js的中(Collection

2019-09-17 20:58发布

我有collection.get和model.get返回undefined问题。

这里是我的initializecode

initialize: function () {
    this.collection = new productsCollection();
    this.model = new productModel();
}

这里是我的渲染代码

this.collection.fetch({
    success: function (product) {
        console.log(product);
        $(that.el).html(_.template(productListTemplate, { products: product.models, _: _ }));
    }
});

我的产品列表中显示的罚款。 当我在每个产品上点击我得到其中名称可以改变一个弹出

我想在模型中,并触发保存,以获得新的设置名称

但我无法得到这里的产品模型的代码

$("#productName").val($(e.currentTarget).html());

var ID = $(e.currentTarget).data("id");
var item = this.collection.get(ID);

console.log("start..........");
console.log(item);
console.log(ID)
//            console.log(this.collection);
console.log(this.model.get(item));
console.log("end..........");

$('.modal').modal('toggle');

我能够得到正确的ID在控制台,但没有收藏和模型

可有人帮助,在此先感谢

在这里更新是完整的视图代码

function ($, _, Backbone, popupModal, productTab, productsCollection, productListTemplate, productModel) {
    var productListView = Backbone.View.extend({
        el: $("#page"),
        initialize: function () {
            this.collection = new productsCollection();
            this.model = new productModel();
            this.model.bind('change', this.loadResults, this);
        },
        render: function () {
            this.loadResults();
        },
        loadResults: function () {
            var that = this;
            this.collection.fetch({
                success: function (product) {
                    console.log(product);
                    $(that.el).html(_.template(productListTemplate, { products: product.models, _: _ }));
                }
            });
            var modalWindow = $(".modal").modal({
                show: false,
                backdrop: true,
                closeOnEscape: true
            });
            $('#createProduct').click(function (e) {
                this.modalWindow.modal('show');
            });
        },
        // This will simply listen for scroll events on the current el
        events: {
            "click #saveProduct": "saveProduct",
            "click .productTabs": "productTabs",
            "click .productDetails": "productDetails"
        },
        saveProduct: function () {
            this.model.set({
                Name: $('#productName').val()
            });
            this.model.save({ id: this.model.get('id') },
         {
             success: function (model, response) {
                 //                 console.log("success");
             },
             error: function (model, response) {
                 //                 console.log(response);
                 var errorMsg = JSON.parse(response.responseText);
                 $(".errorMessage").html('<div class="alert alert-error">' + errorMsg.Error + '</div>');
             }
         });
        },
        productTabs: function (e) {
            e.preventDefault();
            $(this).tab('show');
        },
        productDetails: function (e) {
            e.preventDefault();
            $("#productName").val($(e.currentTarget).html());
            var ID = $(e.currentTarget).data("id");
            var item = this.collection.get(ID);
            console.log("start..........");
            console.log(item);
            console.log(ID)
            //            console.log(this.collection);
            console.log(this.collection.models.get(item));
            console.log("end..........");
            $('.modal').modal('toggle');
        }
    });
    return new productListView;
});

UPDATE回应

this.collection

b.hasOwnProperty.e
_byCid: Object
_byId: Object
_onModelEvent: function () { [native code] }
_removeReference: function () { [native code] }
length: 2
models: Array[2]
0: b.hasOwnProperty.e
1: b.hasOwnProperty.e
length: 2
__proto__: Array[0]
__proto__: s​

它有2种型号,我的清单上还有2个产品

this.model

_callbacks: Object
_changed: false
_changing: false
_escapedAttributes: Object
_previousAttributes: Object
attributes: Object
ID: ""
Name: ""
hRef: ""
__proto__: Object
cid: "c2"
__proto__: s

属性是空的

给了我以下

cid: "view1"
collection: b.hasOwnProperty.e
_byCid: Object
_byId: Object
_onModelEvent: function () { [native code] }
_removeReference: function () { [native code] }
length: 2
models: Array[2]
__proto__: s
model: b.hasOwnProperty.e
_callbacks: Object
_changed: false
_changing: false
_escapedAttributes: Object
_previousAttributes: Object
attributes: Object
cid: "c2"
__proto__: s
options: Object
__proto__: s

UPDATE这是我看到的时候我扩大我的收藏

b.hasOwnProperty.e
_byCid: Object
_byId: Object
_onModelEvent: function () { [native code] }
_removeReference: function () { [native code] }
length: 2
models: Array[2]
0: b.hasOwnProperty.e
_callbacks: Object
_changed: false
_changing: false
_escapedAttributes: Object
_previousAttributes: Object
attributes: Object
ID: "7e0c94fc-7c16-45c9-84a9-a0690103b946"
Name: "dsa"
hRef: "Product/dsa"
__proto__: Object
cid: "c3"
collection: b.hasOwnProperty.e
__proto__: s
1: b.hasOwnProperty.e
length: 2
__proto__: Array[0]
__proto__: s

Answer 1:

问题是,你必须绑定所有功能,将通过DOM事件来电,来您的视图的实例:

所以,加入这行到你的initialize方法:

_.bindAll(this, "saveProduct", "productTabs", "productDetails")

否则, this在功能将是全球性的window对象,而不是你的观点的实例。



Answer 2:

如果

Collection.findWhere({_id: ID}) // get the right answer

我们可以得出这样的结论:

  • 以型号,关键是idAttribute
  • 为Collection,关键是modelId

例如 :

var Model = Backbone.Model.extend();
var Col = Backbone.Collection.extend({ model: Model });

var Persons = new Col([{
    _id: 1,
    name: 'Ken'
}, {
    _id: 2,
    name: 'Mike'
}, {
    _id: 3,
    name: 'John'
}]);

console.log( Persons.get(1) ); // undefined

如果表明M的idAttribute:

var M = Backbone.Model.extend({ idAttribute: '_id' });
...
console.log( Persons.get(1) ); // the model of Ken

在一些场合,我们不需要型号,如:

var Col = Backbone.Collection.extend();

var Persons = new Col([{
    _id: 1,
    name: 'Ken'
}, {
    _id: 2,
    name: 'Mike'
}, {
    _id: 3,
    name: 'John'
}]);

console.log( Persons.get(2) ); // undefined

为了解决这个,我们只需要重写原来modelId方法:

var Col = Backbone.Collection.extend({
    modelId: function() {
        return '_id';
    }
});
...
console.log( Persons.get(2) ); // the model of Mike


PS:更详细的官方文档 。


再PS:BackboneJS的旧版本不支持modelId



文章来源: Collection.get returning undefined in backbone.js