adding custom function into kendo observable array

527 Views Asked by At

How do I add custom or extend kendo observable array ? JS fiddle : 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);
});
1

There are 1 best solutions below

2
On

You should not extend Array but kendo.data.ObservableArray. Your code should be something like:

$(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);
});

Your JSFiddle modified here: http://jsfiddle.net/OnaBai/mctyswh2/8/