Refactored some stuff.

This commit is contained in:
Alan Johnson
2010-08-07 21:46:41 -04:00
parent e373f08bd1
commit a9dfa3605c
+58 -57
View File
@@ -7,6 +7,64 @@ Handlebars = {
isFunction: function(fn) {
return toString.call(fn) === "[object Function]";
},
buildContext: function(context, stack) {
var contextWrapper = function(stack) {
this.__stack__ = stack;
this.__get__ = function(path) {
var context = this;
var parsedPath = Handlebars.parsePath(path);
var depth = parsedPath[0];
var parts = parsedPath[1];
if (depth > 0) {
context = this.__stack__[stack.length - depth];
}
for (var i = 0; i < parts.length; i++) {
context = context[parts[i]];
}
return context;
};
};
contextWrapper.prototype = context;
return new contextWrapper(stack);
},
// Returns a two element array containing the numbers of contexts to back up the stack and
// the properties to dig into on the current context
parsePath: function(path) {
if (path == null) {
return [0, []];
}
var parts = path.split("/");
var readDepth = false;
var depth = 0;
var dig = [];
for (var i = 0; i < parts.length; i++) {
switch(parts[i]) {
case "..":
if (readDepth) {
throw new Handlebars.ParseError("Cannot jump out of context after moving into a context.");
} else {
depth += 1;
}
break;
case ".":
// do nothing - using .'s is pretty dumb, but it's also basically free for us to support
case "this":
// if we do nothing you'll end up sticking in the same context
break;
default:
readDepth = true;
dig.push(parts[i]);
}
}
return [depth, dig];
}
}
@@ -24,63 +82,6 @@ Handlebars.ParseError = function(message) {
this.message = message;
};
Handlebars.buildContext = function(context, stack) {
contextWrapper = function(stack) {
this.__stack__ = stack;
this.__get__ = function(path) {
var context = this;
var parsedPath = Handlebars.parsePath(path);
var depth = parsedPath[0];
var parts = parsedPath[1];
if (depth > 0) {
context = this.__stack__[stack.length - depth];
}
for (var i = 0; i < parts.length; i++) {
context = context[parts[i]];
}
return context;
};
}
contextWrapper.prototype = context;
return new contextWrapper(stack);
};
// Returns a two element array containing the numbers of contexts to back up the stack and
// the properties to dig into on the current context
Handlebars.parsePath = function(path) {
if (path == null) {
return [0, []];
}
var parts = path.split("/");
var readDepth = false;
var depth = 0;
var dig = [];
for (var i = 0; i < parts.length; i++) {
switch(parts[i]) {
case "..":
if (readDepth) {
throw new Handlebars.ParseError("Cannot jump out of context after moving into a context.");
} else {
depth += 1;
}
break;
case ".":
// do nothing - using .'s is pretty dumb, but it's also basically free for us to support
case "this":
// if we do nothing you'll end up sticking in the same context
break;
default:
readDepth = true;
dig.push(parts[i]);
}
}
return [depth, dig];
};
Handlebars.helperMissing = function(object, fn) {
var ret = "";