Knockout - 无法解析绑定

时间:2014-04-19 18:10:29

标签: javascript knockout.js

Chrome网页开发者控制台在页面打开时出错:

Uncaught Error: Unable to parse bindings.
Message: SyntaxError: Unexpected token .;
Bindings value: business.RegistrationViewModel.registerBusiness 

我有一个简单的商业登记表: 我的业务注册按钮data-binds =“business.RegistrationViewModel.registerBusiness”

我的企业RegistrationViewModel如下所示:

var business = {};
business.RegistrationViewModel = function (business)
{
    var me = this;
    me.BusinessName = ko.observable('');
    me.BusinessAddress = ko.observable('');
    me.BusinessCity = ko.observable('');
    me.BusinessState = ko.observable('');
    me.BusinessZip = ko.observable('');
    me.RegistrationEmail = ko.observable('');
};

我的注册功能是:

business.RegistrationViewModel.registerBusiness = function () {
    var me = this;
    var business = ko.toJSON(this);
    $.ajax({
        url: "/RegisterBusiness",
        type: 'post',
        data: business,
        contentType: 'application/json',
        success: function (result) {
            alert("An email has been sent to your email address.");
        }
    });
};

我的applyBinding功能是:

  $(document).ready(function () {
    ko.applyBindings(new business.RegistrationViewModel());
});

我没有正确编写registerBusiness函数吗?我对这个实际错误存在的地方感到很遗憾。

1 个答案:

答案 0 :(得分:2)

registerBusiness()应该是business.RegistrationViewModel的原型,所以要像这样定义......

business.RegistrationViewModel.prototype.registerBusiness = function () {
    var me = this;
    // ...
}

此外,由于ko.applyBindings()的视图模型是business.RegistrationViewModel,因此您无法将其作为绑定的一部分包含在内。只需使用属性的名称......

data-bind="click: registerBusiness"

JsFiddle

编辑:

registerBusiness()的原始声明:

business.RegistrationViewModel.registerBusiness = function () {

将函数放在business.RegistrationViewModel上,而不放在任何实例上。如果你已经完成了Java或C#,那就像声明一个静态方法。要声明类似于实例方法的内容,有2个选项。一种是在每个实例上放置registerBusiness()的副本......

business.RegistrationViewModel = function (business)
{
    var me = this;
    // ...
    me.registerBusiness = function () {
        // ...
    };
};

因为每个实例都有一个副本,如果创建了大量RegistrationViewModel,内存可能会成为一个问题。另一种选择是在原型上声明方法,该方法只创建一次但每个实例都可以访问...

business.RegistrationViewModel.prototype.registerBusiness = function () {
    // ...
}