【问题标题】:Custom compileService for caching link functions自定义 compileService 用于缓存链接功能
【发布时间】:2014-09-15 15:16:52
【问题描述】:

我正在使用AngularJSTypeScript,并且我正在尝试创建自己的编译服务,该服务将具有缓存机制。

现在我的服务很简单: 它输入一个 html 字符串,创建一个哈希键,检查它是否存在于缓存中。 如果存在,则返回缓存的链接函数,否则创建链接函数,缓存并返回。

看起来像这样:

// found this on the internet..
private createHashKey(html: string): number {
    var hash = 0, i, chr, len;
    if (html.length == 0) return hash;
    for (i = 0, len = html.length; i < len; i++) {
        chr = html.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }

    return hash;
}

public compile(html: string): ng.ITemplateLinkingFunction {
    var key = this.createHashKey(html);

    if (!this.compiledCache.containsKey(key)) {
        this.compiledCache.setValue(key, this.$compile(html));
    }

    return this.compiledCache.getValue(key);
}

现在我一直用compileService.compile(html)替换我所有的$compile(html)调用,直到我得到一个不将字符串作为输入参数传递,而是传递JQuery对象的调用。

我查看了angular.d.ts 文件并发现了这个:

interface ICompileService {
    (element: string, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;
    (element: Element, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;
    (element: JQuery, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;
}

垃圾!!!!!

所以现在我需要支持三个compile 重载。 现在,由于从 JQuery 对象创建哈希键与 string 不同,我不能提供这样的“虚拟重载”:

public compile(element: JQuery);
public compile(element: Element);
public compile(element: string);
public compile(html: any): ng.ITemplateLinkingFunction {
    var key = this.createHashKey(html); // this will not work with JQuery objects

    if (!this.compiledCache.containsKey(key)) {
        this.compiledCache.setValue(key, this.$compile(html));
    }

    return this.compiledCache.getValue(key);
}

所以我有两个问题:

  1. 有什么方法可以将compile 函数名保留在多个实现中?我想答案是否定的,因为我了解Typescript 的工作原理,但也许这里有一个解决方法。我不想创建像 compileJQuerycompileHtml 这样的方法名称。

  2. 我需要想出一种优雅的方法来散列 JQueryElement 对象作为我的键,并使其非常高效。

任何额外的提示也会很棒。

【问题讨论】:

    标签: javascript angularjs caching hash typescript


    【解决方案1】:

    你可以用 var key = this.createHashKey(html); 代替:

    var strVal = html;
    if(html instanceof jQuery) strVal = html.html();
    
    var key = this.createHashKey(strVal);
    

    【讨论】:

    • 已经试过了。html() 出于某种奇怪的原因是空的,而 html 对象是包含文本和 html 元素的 8 个元素的数组。
    • 如果它是一个数组,你可以做类似foo.length &gt; 1 ? foo.each(function(){ strVal = strVal + this.html() }) : foo.html() 但它开始看起来很狡猾
    • 确切的类型是jQuery.fn.jQuery.init[8]。这是编译的代码:$compile(element.contents())(scope); 其中 elements 是链接函数接受的第二个参数:this.link = function (scope, element, attr)
    • $compile 方法有 3 个重载,其中没有一个是数组。我不知道Element 是什么,但它也有过载。顺便说一句,你对连接的建议是我开始做的,但我认为它太可疑了,无法继续,我可能在这里遗漏了一些小东西。
    猜你喜欢
    • 1970-01-01
    • 2018-03-03
    • 2016-12-31
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    相关资源
    最近更新 更多