JsRender / JsViews:如何让{for}为子类阵列工作

时间:2015-03-11 11:55:55

标签: typescript jsrender jsviews

我已经将Array(使用TypeScript)子类化,以便能够向Array添加额外的功能。请参阅下面的代码。

从那时起,我注意到JsRender / JsViews的{for}标签不再起作用了。 我还注意到JsRender / JsViews使用$.isArray(...)来迭代数组,这将在子类数组上返回false

当我更改JsRender / JsViews代码以使用(data instanceof Array)时,它确实有效。

是否有其他方法(不更改JsRender / JsViews代码)以使子类化数组与JsRender / JsViews {for}标记一起使用?

打字稿:

module MyModule {
    export class Collection<T> implements Array<T> {
        constructor() {
            Array.apply(this, arguments);
            return new Array();
        }

        length: number;
        toString(): string { return ""; }
        //... All other Array properties/methods
    }

    // replace dummy declarations with the real thing
    Collection['prototype'] = new Array();
}

生成的Javascript:

var MyModule;
(function (MyModule) {
    var Collection = (function () {
        function Collection() {
            Array.apply(this, arguments);
            return new Array();
        }

        Collection.prototype.toString = function () { return ""; };
        //... All other Array properties/methods

        return Collection;
    })();
    MyModule.Collection = Collection;

    // replace dummy declarations with the real thing
    Collection['prototype'] = new Array();
})(MyModule|| (MyModule= {}));

1 个答案:

答案 0 :(得分:2)

您的SubclassedCollection不是JavaScript数组(就像jQuery对象不是JavaScript数组一样)。与您的收藏集不同,它会从"[object Object]"返回Object.prototype.toString.call(ob) - 而不是"[object Array]"

一种可能的方法可能是使用该功能:

function toArray(ob) {
    return Array.prototype.slice.call(ob);
}

并写入

MyModule.ViewModel = { Coll: toArray(collection2) };

或者将toArray注册为帮助者(~toArray)或转换器("toArray"),然后将模板写为:

{{for ~toArray(Coll)}}

(或{{for Coll convert=~toArray}}{{for Coll convert="toArray"}})。

以下是jsfiddle的更新分支:http://jsfiddle.net/16L670re/