1

我对 Array 进行了子类化(使用 TypeScript),以便能够向 Array 添加额外的函数。请参阅下面的代码。

从那以后,我注意到{for}JsRender/JsViews 的标签不再起作用了。我还注意到 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= {}));
4

1 回答 1

2

您的 SubclassedCollection 不是 JavaScript 数组(就像 jQuery 对象不是 JavaScript 数组一样)。与您的 Collection 不同,它"[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/

于 2015-03-12T22:26:19.260 回答