Collection.get returning undefined in backbone.js

Collection.get returning undefined in backbone.js

本文关键字:backbone js in undefined get returning Collection      更新时间:2023-09-26

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

这是我的初始化代码

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,但不能在集合和模型中获得正确的 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;
});

更新响应

这个.收藏

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 个产品

这个模型

_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

更新这是我在扩展收藏时看到的

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

问题是您必须将所有将由 DOM 事件调用的函数绑定到视图的实例:

因此,请将此行添加到您的initialize方法中:

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

否则,函数中的this将是全局window对象,而不是视图的实例。

if

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

我们可以得出结论:

  • 到模型,键是 idAttribute
  • 到集合,键是模型 ID

例如:

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 :官方文档中的更多详细信息。


P.S.再次:旧版本的BackboneJS不支持modelId