为什么我得到self.description(...)未定义?

时间:2014-05-30 21:28:03

标签: javascript jquery knockout.js

我已经开始使用Knockout JS并且我将textarea计数器应用于我的viewmodel。但由于某种原因,我收到错误消息:

  

TypeError:self.description(...)未定义
  var counter = self.description()。length;

即使我的teset fiddle也不起作用。

我的代码是:

//HTML
<textarea data-bind="value: description, valueUpdate: 'afterkeydown'"></textarea>

//JS
jQuery(document).ready(function($) {
    ko.applyBindings(specialOfferPreviewModel());
});

function specialOfferPreviewModel() {

// -- This part works
    var self = this;
    self.promoTitle = ko.observable();
    self.description = ko.observable();
    self.fromDate = ko.observable();
    self.toDate = ko.observable();

    // To and from date
    self.validPeriod = ko.computed(function() {
        return self.fromDate + " - " + self.toDate;
    }, self);


// -- And this part breaks it
    self.count = ko.computed(function(){
        var counter = self.description().length;
        return counter;
    });
}

我错过了什么?任何帮助表示赞赏!

更新:

我不确定这两者的区别,但要么有效:

//1
function specialOfferPreviewModel(){}
ko.applyBindings(specialOfferPreviewModel());

//2
var specialOfferPreviewModel = function(){}
var vm = new specialOfferPreviewModel ();
ko.applyBindings(vm);

他们都工作

1 个答案:

答案 0 :(得分:1)

因为observable包含undefined,因为它尚未设置。

写下:

self.description = ko.observable();

observable包含undefined,如果你按如下方式分解代码,你可以看到它:

self.description = ko.observable();
var content = self.description();
content.length;

小提琴:

var counter = self.description().length;

在绑定到字段之前进行评估,这就是它的内部值未定义的原因。

所以你可以初始化observable:

self.description = ko.observable('');

或者您可以推迟计算的评估:

self.count = ko.computed({
    read: function () {
         var counter = self.description().length;
         return counter;
    },
    deferEvaluation: true
});

See doc

相关问题