javascript – 当在当前的一个中找不到时,Mustache js获取父对象的范围

前端之家收集整理的这篇文章主要介绍了javascript – 当在当前的一个中找不到时,Mustache js获取父对象的范围前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
根据胡子RFC

A {{name}} tag in a basic template will try to find the name key in
the current context. If there is no name key,nothing will be
rendered.

因此我期待这样:

  1. var template = '{{#anArray}}{{aString}}{{/anArray}}';
  2.  
  3. var json = {
  4. "aString":"ABC","anArray": [1,{"aString":"DEF"}]
  5. };

给我一次渲染:

  1. "DEF"

但是,mustache.js会在父级范围内查找值.这给了我

  1. "ABCDEF"

上下文实际上意味着包括所有父母范围吗?

http://jsfiddle.net/ZG4zd/20/

解决方法

简短回答:是的.

更长的答案. Context.prototype.lookup执行while循环,在当前上下文中查找标记,并且它是父上下文,同时存在父上下文.

相关的代码

  1. Context.prototype.lookup = function (name) {
  2. var value = this._cache[name];
  3.  
  4. if (!value) {
  5. if (name === ".") {
  6. value = this.view;
  7. } else {
  8. var context = this;
  9.  
  10. //Iterate ancestor contexts
  11. while (context) {
  12. if (name.indexOf(".") > 0) {
  13. var names = name.split("."),i = 0;
  14.  
  15. value = context.view;
  16.  
  17. while (value && i < names.length) {
  18. value = value[names[i++]];
  19. }
  20. } else {
  21. value = context.view[name];
  22. }
  23.  
  24. if (value != null) {
  25. break;
  26. }
  27.  
  28.  
  29. context = context.parent;
  30. }
  31. }
  32.  
  33. this._cache[name] = value;
  34. }
  35.  
  36. if (typeof value === "function") {
  37. value = value.call(this.view);
  38. }
  39.  
  40. return value;
  41. };

猜你在找的JavaScript相关文章