当我执行以下代码时,它给我上面的错误?

时间:2017-02-18 12:24:24

标签: javascript jquery html knockout.js

Uncaught ReferenceError: Unable to process binding "value: function (){return sumValBinding }" Message: sumValBinding is not defined

这是我的HTML:

<div class="form-group">
                <label for="inputdefault">First number</label>
                <input class="form-control" id="Textbox1" type="text">
            </div>
            <div class="form-group">
                <label for="inputdefault">Second number</label>
                <input class="form-control" id="Textbox2" type="text">
            </div>
            <div class="form-group">
                <label for="inputdefault">Answer</label>
                <input class="form-control" id="TextboxSum" type="number" data-bind="value:sumValBinding">
            </div>
            <button type="button" class="btn btn-default" id="submit">Submit</button>

=============================================== =============================== 这里是Javascript / Knockout JS enter code here

$("#submit").click(function (e) {
        debugger;
        number1 = parseInt(document.getElementById("Textbox1").value);
        number2 = parseInt(document.getElementById("Textbox2").value);
        sumOfTwoNumber = number1 + number2;
        console.log(parseInt(number2));
        //v = new viewModel();
        ko.applyBindings(new viewModel(), document.getElementById("TextboxSum"));
    });
    var viewModel = function()
    {
        sumValBinding: ko.observable(sumOfTwoNumber) // Prepopulate
        };

1 个答案:

答案 0 :(得分:0)

您的视图模型是一个构造函数,因此,如果您希望在对象实例中具有该属性,则应为其指定属性:

var viewModel = function() {
    this.sumValBinding = ko.observable(sumOfTwoNumber);
};

或您的构造函数可以返回一个对象:

var viewModel = function() {
    return {
       sumValBinding: ko.observable(sumOfTwoNumber);
    };
};