Вопрос

I have this code which I have found from google. It's a adapter for agility.js restful model for saving data. Now the DELETE function works perfectly except on the _params.id === 0 where it would say

Uncaught TypeError: Cannot set property 'id' of undefined

The code

$$.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();
};
Это было полезно?

Решение

I found a solution, it's in how the function detect the error at the line if (!_params.id) which also return false for "0" so the correct code is

$$.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();
};
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top