Skip to content

Commit

Permalink
[minor] Move the replacer out of the pagelet rendering
Browse files Browse the repository at this point in the history
[major] Move pagelet.data to it's own `{fittings:state}` variable.
  • Loading branch information
3rd-Eden committed Mar 6, 2015
1 parent 9a7e027 commit 8030572
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,25 @@ function generator() {
return Math.random().toString(36).substring(2).toUpperCase();
}

/**
* Replacer for JSON so the resulting object can safely be loaded in a script
* tag without crashing.
*
* @param {String} key key that we're replacing.
* @param {Mixed} data
* @api private
*/
function replacer(key, data) {
if ('string' !== typeof data) return data;

return data
.replace(/&/gm, '&')
.replace(/</gm, '&lt;')
.replace(/>/gm, '&gt;')
.replace(/"/gm, '&quot;')
.replace(/'/gm, '&#x27;');
}

/**
* A pagelet is the representation of an item, section, column or widget.
* It's basically a small sandboxed application within your application.
Expand Down Expand Up @@ -896,7 +915,8 @@ Pagelet.readable('render', function render(options, fn) {
, bigpipe = this._bigpipe
, temper = this._temper
, query = this.query
, pagelet = this;
, pagelet = this
, state = {};

/**
* Write the fragmented data.
Expand All @@ -923,19 +943,11 @@ Pagelet.readable('render', function render(options, fn) {
client: temper.fetch(pagelet.view).hash.client
};

data = pagelet.stringify(data, function sanitize(key, data) {
if ('string' !== typeof data) return data;

return data
.replace(/&/gm, '&amp;')
.replace(/</gm, '&lt;')
.replace(/>/gm, '&gt;')
.replace(/"/gm, '&quot;')
.replace(/'/gm, '&#x27;');
});
data = pagelet.stringify(data, replacer);

fn.call(context, undefined, framework.get('fragment', {
template: content.replace(/<!--(.|\s)*?-->/, ''),
state: pagelet.stringify(state, replacer),
name: JSON.stringify(pagelet.name),
id: JSON.stringify(pagelet.id),
data: data
Expand Down Expand Up @@ -1003,7 +1015,7 @@ Pagelet.readable('render', function render(options, fn) {
// Add queried parts of data, so the client-side script can use it.
//
if ('object' === typeof result && Array.isArray(query) && query.length) {
data.data = query.reduce(function find(memo, q) {
state = query.reduce(function find(memo, q) {
memo[q] = dot.get(result, q);
return memo;
}, {});
Expand Down

0 comments on commit 8030572

Please sign in to comment.