Chrome Web开发人员控制台在打开页面时出现错误:

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


我有一个简单的商业登记表:
我的商业注册按钮数据绑定=“ business.RegistrationViewModel.registerBusiness”

我的商务注册视图模型如下所示:

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函数吗?我不知道这个实际错误在哪里。

最佳答案

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

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


另外,由于赋予ko.applyBindings()的viewmodel是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 () {
    // ...
}

09-26 23:54