Vulcan/packages/vulcan-lib/lib/client/inject_data.js

36 lines
948 B
JavaScript
Raw Normal View History

2017-02-06 14:33:34 +08:00
import { Meteor } from 'meteor/meteor';
import { EJSON } from 'meteor/ejson';
2017-02-12 22:00:13 +08:00
// InjectData object
2017-02-06 14:33:34 +08:00
export const InjectData = {
2017-02-12 22:00:13 +08:00
// data object
2017-02-06 14:33:34 +08:00
_data: {},
2017-02-12 22:00:13 +08:00
// encode object to string
2017-02-06 14:33:34 +08:00
_encode(ejson) {
const ejsonString = EJSON.stringify(ejson);
return encodeURIComponent(ejsonString);
},
2017-02-12 22:00:13 +08:00
// decode string to object
2017-02-06 14:33:34 +08:00
_decode(encodedEjson) {
const decodedEjsonString = decodeURIComponent(encodedEjson);
if (!decodedEjsonString) return null;
return EJSON.parse(decodedEjsonString);
},
2017-02-12 22:00:13 +08:00
// get data when DOM loaded
2017-02-06 14:33:34 +08:00
getData(key, callback) {
Meteor.startup(() => {
callback(this._data[key]);
});
},
};
2017-02-12 22:00:13 +08:00
// when DOM loaded, decode string from <script> and save the data
2017-02-06 14:33:34 +08:00
Meteor.startup(() => {
const dom = document.querySelector('script[type="text/inject-data"]');
const injectedDataString = dom ? dom.textContent.trim() : '';
InjectData._data = InjectData._decode(injectedDataString) || {};
});