2015-01-04 4 views
2

IndexedDB에서 형식이 지정된 Javascript 객체를 저장하고 검색하는 가장 효율적인 방법은 무엇입니까?IndexedDB에서 형식화 된 객체 검색

문제는 IndexedDB는 프로토 타입 정보를 저장하지 않으므로 일반 개체 (또는 배열 또는 프리미티브 또는 몇 가지 다른 유형) 만 저장하고 검색 할 수 있다는 것입니다. 해결 방법은 데이터베이스에서 검색 한 개체에 __proto__을 명시 적으로 할당하는 것입니다. 예를 들어, 내가

game.__proto__ = Game.prototype; 

않는 Game 개체를 가져 그러나, __proto__ 할당은 실제로는 지원하지만 그것이 A) 기술적 비표준 인 문제를 가지고 있으며, B)는 코드를 deoptimizes. 사실, 파이어 폭스는 명시적인 경고를한다.

[[프로토 타입]] 개체를 변경하면 코드가 매우 느리게 실행된다. 대신 Object.create를 사용하여 정확한 초기 [[Prototype]] 값으로 객체를 생성하십시오.

분명히 Object.create은 여기에 해당되지 않습니다. __proto__ 과제에 대한 더 나은 대안이 있습니까?

+0

JSON.stringify를 사용하여 객체를 문자열로 저장 한 다음 나중에 JSON.parse를 사용하여 다시 가져올 수 있습니까? – codelion

답변

3

자체 데이터 개체 자체 만 저장할 수도 있습니다. 게임은 저장 가능한 대상의 프록시가됩니다.

function Game(props) { 
    this.props = props || {}; 
} 

// An example of property decoration 
Game.prototype.set x(value) { 
    this.props.x = value; 
}; 
Game.prototype.get x() { 
    return this.props.x; 
}; 

// Use this when initializing a game after retrieving game data from indexedDB store. 
// e.g. when creating a new game, use var newGame = Game.fromSerializable(props); 
Game.fromSerializable = function(props) { 
    return new Game(props); 
}; 

// When it comes time to persist the game object, expose the serializable props object 
// so that the caller can pass it to store.put/store.add 
Game.prototype.toSerializable = function() { 
    return this.props; 
}; 

이것은 읽기/쓰기에 대한 색인화가 사용하는 구조화 된 복제 알고리즘을 통해 통과, 또는 다른 사람들이 이해하기 위해 투쟁 수도 이상한 일회성를 해킹 사용 할 수 있는지를 다루는 귀찮게보다 간단 수 있습니다.