0

如何添加自定义或扩展剑道可观察数组?JS 小提琴:http: //jsfiddle.net/balarvs/mctyswh2/3/

$(document).ready(function () {
/*   var ar = [
    { id: "10" }, 
    { id: "12" },
    { id: "20" }
]; */

if (![].getById) {
    Array.prototype.getById = function (id) {
        'use strict';
        var arr = Object(this);
        var found;
        for (var i = 0; i < arr.length; i++) {
            var item = arr[i];
            if (item.id == id) {
                found = item;
            }
        }
        return found;
    };
}
var obser=new kendo.data.ObservableArray( [
    { id: "10" },
    { id: "12" },
    { id: "20" }
]);
var bb = obser.getById("20");
if (bb != undefined) console.log(bb.id);
});
4

1 回答 1

0

你不应该扩展Arraybut kendo.data.ObservableArray。你的代码应该是这样的:

$(document).ready(function () {
    kendo.data.ObservableArray.prototype.getById = function (id) {
        'use strict';
        var arr = Object(this);
        var found;
        for (var i = 0; i < arr.length; i++) {
            var item = arr[i];
            if (item.id == id) {
                found = item;
            }
        }
        return found;
    };

    var obser=new kendo.data.ObservableArray( [
        { id: "10" },
        { id: "12" },
        { id: "20" }
    ]);
    var bb = obser.getById("23");
    if (bb != undefined) console.log(bb.id);
});

您的 JSFiddle 在这里修改:http: //jsfiddle.net/OnaBai/mctyswh2/8/

于 2015-02-03T17:06:34.097 回答