Backbone fetch返回我模型的所有实例

时间:2013-08-31 21:20:30

标签: javascript backbone.js

我有以下代码,它应该在我的模型中获取一个对象并使用模板呈现它:

 productDetails: function (id) {
        var product = new app.models.Product({id: id});
        product.fetch({
            success: function (data) {
                console.log(data);
                app.slider.slidePage(new app.views.ProductView({model: data}).render().$el);
            }
        });
    }

但是,出于某种原因,data是我所有模型对象的列表:

attributes: Object
0: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
10: Object
11: Object
12: Object
13: Object
...
id: "73"

我是Backbone的新手,所以我不知道是什么原因造成的......

您需要更多代码吗?

ProductModel.js

app.models.Product = Backbone.Model.extend({

    initialize: function () {
    },

    sync: function (method, model, options) {
        if (method === "read") {
            app.adapters.product.findById(parseInt(this.id)).done(function (data) {
                options.success(data);
            });
        }
    }

});

app.models.ProductCollection = Backbone.Collection.extend({

    model: app.models.Product,

    sync: function (method, model, options) {
        if (method === "read") {
app.adapters.product.findByName(options.data.name).done(function (data) {
                options.success(data);
            });
        }
    }

});

1 个答案:

答案 0 :(得分:1)

您的adapters.product可能是指该集合,然后在您的产品sync函数中返回该集合。

解决方案是这样的:

var findById = function (id) {
  var deferred = $.Deferred();
  var product = null;
  var l = products.length;
  for (var i = 0; i < l; i++) {
    if (products[i].id === id) {
      product = products[i];
      break;
    }
  }
  deferred.resolve(product);   // HERE WAS product__s__
  return deferred.promise();
}