2012-03-29 52 views
0

我有我從google找到的這段代碼。它是用於保存數據的agility.js寧靜模型的適配器。現在,刪除功能完美的作品除了在_params.id === 0它會說Agility.js本地存儲功能

Uncaught TypeError: Cannot set property 'id' of undefined

$$.adapter.localStorage = function(_params) { 
    var key = (this._data.persist.baseUrl || '') + this._data.persist.collection; 
    var value = localStorage[key]; 
    var items = (value && value.length > 0 ? JSON.parse(value) : []); 
    switch (_params.type) { 
    case 'GET': 
     if (_params.id) { // normal get 
      if (items[_params.id]) { 
       _params.success(items[_params.id]); 
      } else { 
       _params.error(); 
      } 
     } else { // gather call 
      console.log(items); 
      items = $.map(items, function(item) { 
       return item; 
      }); 
      console.log(items); 
      _params.success(items); 
     } 
     break; 
    case 'DELETE': 
     _params.data = undefined; // continue into POST case 
    case 'PUT': 
     // continue into POST case 
    case 'POST': 
     if (!_params.id) { 
      _params.id = items.length; 
      _params.data.id = _params.id; 
     } 
     items[_params.id] = _params.data; 
     //_params.success({id:_params.id}); 
     localStorage[key] = JSON.stringify(items); 
     break; 
    } 
    _params.complete(); 
}; 

回答

0

我找到了一個解決方案的代碼,它在功能如何檢測錯誤在該行if (!_params.id)也返回假爲「0」,所以正確的代碼是

$$.adapter.localStorage = function(_params) { 
    var key = (this._data.persist.baseUrl || '') + this._data.persist.collection; 
    var value = localStorage[key]; 
    var items = (value && value.length > 0 ? JSON.parse(value) : []); 
    switch (_params.type) { 
    case 'GET': 
     if (_params.id) { // normal get 
      if (items[_params.id]) { 
       _params.success(items[_params.id]); 
      } else { 
       _params.error(); 
      } 
     } else { // gather call 
      console.log(items); 
      items = $.map(items, function(item) { 
       return item; 
      }); 
      _params.success(items); 
     } 
     break; 
    case 'DELETE': 
     _params.data = undefined; // continue into POST case 
    case 'PUT': 
     // continue into POST case 
    case 'POST': 
     if (!_params.id && _params.id !== 0) { 
      _params.id = items.length; 
      _params.data.id = _params.id; 
     } 
     items[_params.id] = _params.data; 
     //_params.success({id:_params.id}); 
     localStorage[key] = JSON.stringify(items); 
     break; 
    } 
    _params.complete(); 
};