xxx不是我的ViewModel中的函数

时间:2015-07-31 18:44:19

标签: javascript knockout.js

为什么我得到Uncaught TypeError: this.createRow is not a function 在matrixLengthsAvailable数组构造?

我的viewmodel ...

结束时声明了createRow函数
function TabBuyHarvesterModel() {
    self = this;

    this.selectedEmote = ko.observable('kappa');
    this.matrixLengthsAvailable = ko.observableArray([
        { length: 10, pctDetails: this.createRow(10) /*ko.mapping.fromJS({ rowLength: 10 })*/ }
        //30,
        //60,
        //180,
        //360,
        //720,
            //1440
        ]);

    this.selectEmote = function (emoteClicked) {
        self.selectedEmote(emoteClicked.emote);
    };

    this.createRow = function (rowLength) {
        var ret = new TabBuyHarvesterMatrixRowModel();
        ret.rowLength(rowLength);
        return ret;
    };
}

4 个答案:

答案 0 :(得分:1)

因为ko.observableArray()是一个函数,this.createRow中的this引用将引用obervableArray上下文,将其更改为self。

答案 1 :(得分:1)

您尝试在创建之前使用createRow功能。在 createRow之前定义matrixLengthsAvailable 。更好的方法是在createRow原型上定义TabBuyHarvesterModel。在您的类实例化之前,它会定义一次该函数。

function TabBuyHarvesterModel() {
    ...
}

TabBuyHarvesterModel.prototype.createRow = function (rowLength) {
    var ret = new TabBuyHarvesterMatrixRowModel();
    ret.rowLength(rowLength);
    return ret;
};

答案 2 :(得分:1)

你应该像已经指出的那样使用self,并在任何地方使用它,然后你需要切换方法的顺序,以便在需要之前定义createRow。

此处:http://jsfiddle.net/oshmn46o/

function TabBuyHarvesterModel() {
var self = this;

self.createRow = function (rowLength) {
    var ret = new TabBuyHarvesterMatrixRowModel();
    ret.rowLength(rowLength);
    return ret;
};

self.selectedEmote = ko.observable('kappa');
self.matrixLengthsAvailable = ko.observableArray([
    { length: 10, pctDetails: self.createRow(10) /*ko.mapping.fromJS({ rowLength: 10 })*/ }
    //30,
    //60,
    //180,
    //360,
    //720,
        //1440
    ]);

self.selectEmote = function (emoteClicked) {
    self.selectedEmote(emoteClicked.emote);
};

}

答案 3 :(得分:1)

If you only reference createRow from inside TabBuyHarvesterModel, then just making it a plain old function will work. Also, if you do this, then you will not have to define createRow before the matrixLengthsAvailable observable because JavaScript always hoists functions to the top of a closure even if they are not defined at the top of the closure:

function TabBuyHarvesterModel() {
    self = this;

    this.selectedEmote = ko.observable('kappa');
    this.matrixLengthsAvailable = ko.observableArray([
        { length: 10, pctDetails: createRow(10) /*ko.mapping.fromJS({ rowLength: 10 })*/ }
        //30,
        //60,
        //180,
        //360,
        //720,
            //1440
        ]);

    this.selectEmote = function (emoteClicked) {
        self.selectedEmote(emoteClicked.emote);
    };

    function createRow(rowLength) {
        var ret = new TabBuyHarvesterMatrixRowModel();
        ret.rowLength(rowLength);
        return ret;
    }
}