微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

因此我期待这样:

var template = '{{#anArray}}{{aString}}{{/anArray}}';

var json = {
    "aString":"ABC","anArray": [1,{"aString":"DEF"}]
 };

给我一次渲染:

"DEF"

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

"ABCDEF"

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

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

解决方法

简短回答:是的.

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

相关的代码

Context.prototype.lookup = function (name) {
    var value = this._cache[name];

    if (!value) {
      if (name === ".") {
        value = this.view;
      } else {
        var context = this;

        //Iterate ancestor contexts
        while (context) {
          if (name.indexOf(".") > 0) {
            var names = name.split("."),i = 0;

            value = context.view;

            while (value && i < names.length) {
              value = value[names[i++]];
            }
          } else {
            value = context.view[name];
          }

          if (value != null) {
            break;
          }


          context = context.parent;
        }
      }

      this._cache[name] = value;
    }

    if (typeof value === "function") {
      value = value.call(this.view);
    }

    return value;
  };

原文地址:https://www.jb51.cc/js/156616.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐