0

在这里,我正在尝试使用ember-model实现 CRUD 操作。我对 ember 环境完全陌生,实际上我对ember-model了解不多。

在这里,我正在尝试添加新产品并删除现有产品。我正在使用fixture ie的内部节点。我的cart_items这个夹具包含两个节点 ie logged_incart_items这就是我的夹具结构:

Astcart.Application.adapter = Ember.FixtureAdapter.create();

Astcart.Application.FIXTURES = [
{
    "logged_in": {
        "logged": true,
        "username": "sachin",
        "account_id": "4214"
    },
    "cart_items": [
    {
        "id": "1",
        "name": "Samsung Galaxy Tab 2",
        "qty": "1",
        "price": "100",
        "subtotal": "100"
    },
    {
        "id": "2",
        "name": "Samsung Galaxy Tab 2",
        "qty": "1",
        "price": "100",
        "subtotal": "100"
    },
    {
        "id": "3",
        "name": "Samsung Galaxy Tab 2",
        "qty": "1",
        "price": "100",
        "subtotal": "100"
    }
    ]           
}
];

我想要这个夹具结构只是为了从服务器的一个服务调用中获取数据。现在,这是我用来添加和删除产品的代码cart_items

Astcart.IndexRoute = Ember.Route.extend({
    model: function() {
        return Astcart.Application.find();
    }
}); 

Astcart.IndexController = Ember.ArrayController.extend({
 save: function(){                    
    this.get('model').map(function(application) {                
        var new_cart_item = application.get('cart_items').create({name: this.get('newProductDesc'),qty: this.get('newProductQty'),price: this.get('newProductPrice'),subtotal: this.get('newProductSubtotal')});                
        new_cart_item.save();
            });
 },    
 deleteproduct: function(product){
    if (window.confirm("Are you sure you want to delete this record?")) {                           
    this.get('model').map(function(application) {
        application.get('cart_items').deleteRecord(product);                    
    });            
  }
}
}); 

但是当我试图保存产品时,我遇到了一个例外

Uncaught TypeError: Object [object global] has no method 'get' 

当我试图删除产品时,我遇到了异常

Uncaught TypeError: Object [object Object] has no method 'deleteRecord'

在这里,我还想实现一个功能,即在每次保存时我需要检查该产品是否已经存在。如果产品不存在,则仅保存新产品,否则明智地更新现有产品。但我不知道该怎么做?

我在这里发布了我的完整代码。 任何人都可以帮助我使这个 jsfiddle 工作吗?

更新

我在这里用调试更新了我的代码。

在这里,我没有得到任何异常,但记录也没有被删除。我不明白这里发生了什么?

任何人都可以帮助我使这个 jsfiddle 工作吗?

4

1 回答 1

0

'this' 上下文在您的保存方法中发生变化。您需要使用控制器的“this”而不是地图功能。尝试这个:

save: function(){
    var self = this;
    self.get('model').map(function(application) {                
        var new_cart_item = application.get('cart_items').create({
                               name: self.get('newProductDesc'),
                               qty: self.get('newProductQty'),
                               price: self.get('newProductPrice'),
                               subtotal: self.get('newProductSubtotal')
                               });                
        new_cart_item.save();
   });
 }
于 2013-09-09T17:57:31.703 回答