在Durandal / SPA应用程序中配置Knockout验证

时间:2013-08-03 13:17:28

标签: knockout.js requirejs single-page-application durandal knockout-validation

我无法获得knockout.validation并使用durandal运行。淘汰赛本身工作正常。如果有人这么做,我会感谢发布配置。

// main.js
require.config({
    paths: {
    "libs": "../scripts",
    "knockout": "../scripts/knockout-2.2.1",
    'knockout.validation': '../scripts/knockout.validation'
},
shim: {
    'knockout.validation': {
        deps: ["knockout"]
    }
}
});

define(function (require) {
validation = require('libs/knockout.validation')
// other dependencies are omitted
ko.validation = validation;
// ko works fine
// ko validation has been set
}

// my viewmodel
define(['services/logger',
'durandal/app',
'durandal/system',
'durandal/plugins/router',
'services/dataservice'],
function (logger, app, system, router, dataservice) {

var user_name = ko.observable().extend( {required: true } );
var user_password = ko.observable().extend( {required: true });

// Unable to get property 'extend' of undefined or null reference
// the same happens, if I define '/libs/knockout.validation locally

kockout.validation的行为是否与其他插件不同?

2 个答案:

答案 0 :(得分:4)

以下是淘汰赛验证和durandal vm的工作示例;

define(['plugins/router', 'durandal/app', 'config'],function (router, app, config) {

    ko.validation.init({
        messagesOnModified: false
    });
    ko.validation.registerExtenders();
    var email = ko.observable().extend({
        required: { message: 'You must enter a valid email id' },
        email: { message: 'Email address you entered is not valid' }
    });
    var password = ko.observable().extend({
        required: { message: 'Enter password, minimum of 6 characters' },
        minLength: 6
    });

    var vm = {
        activate: activate,
        attached: attached,
        router: router,
        email: email,
        password: password,
        signIn: signIn,
        viewUrl : 'signin/index.html'
    };

    vm.errors = ko.validation.group(vm);
    return vm;

    function activate(id, querystring) {}

    function attached(view, parent) { }

    function signIn() {
        if (!vm.isValid()) {
            vm.errors.showAllMessages(true);
            return false;
        }
        //rest of logic         
    }
});

答案 1 :(得分:2)

正如我在评论中提到的那样,目前针对require.js的淘汰验证效果不佳。 Durandal在开发过程中依赖require.js,直到您优化应用程序。

此链接详细介绍了目前的解决方法。

http://github.com/Knockout-Contrib/Knockout-Validation/issues/259