2012-03-29 113 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(); 
};