如何在requirejs中使用knockout加载knockout.validation

时间:2013-08-06 06:04:34

标签: jquery knockout.js requirejs knockout-validation

我将在require js中定义我的模型,我的模块中需要knockoutknockout validation plugin以及jquery。

define(["knockout","jquery","knockout.validation"], function (ko,$,validation) {
  // knockout model here with some knockout validation 

    return function SignUpViewModel() {
    var self = this;
    self.name = ko.observable();
    self.email = ko.observable().extend({ required: true });
    self.password = ko.observable().extend({
       required: true,
       minLength: 6
   });
   self.confirmPassword = ko.observable().extend({ mustEqual: self.password() });
   self.company = ko.observable();
   self.availableCountries = ko.observableArray(['Pakistan', 'USA', 'Egypt', 'UAE']);
   self.selectedCountry = ko.observable();
   self.errors = ko.validation.group(self);
   }           
 });

但是当我运行这个时,我得到了以下错误。

Uncaught ReferenceError: ko is not defined

我也尝试调试,发现所有其他库knockoutjquery正在加载完美。

这是我的配置部分

require.config({
  baseUrl: "/Scripts",
  paths: {
    "Signup" : "Signup",
    "knockout": "knockout-2.3.0",
    "knockout.validation": "knockout.validation",
    "jquery": "require-jquery"
    }
});

2 个答案:

答案 0 :(得分:4)

你的模型和我一起工作正常,这是我的require config:

requirejs.config({
  baseUrl: '/Scripts',
  paths: {
    'jquery': 'jquery-1.9.1.min',
    'knockout' : 'knockout-2.3.0',
  }
});
// myModel.js is the file containing your model code.
require( ["myModel", "knockout"], function(model, ko){
  ko.applyBindings(new model());
});

myModel.js

define(["knockout","jquery","knockout.validation"], function (ko,$,validation) {
// knockout model here with some knockout validation 

  return function SignUpViewModel() {
    var self = this;
    self.name = ko.observable();
    self.email = ko.observable().extend({ required: true });
    self.password = ko.observable().extend({
       required: true,
       minLength: 6
    });
    self.confirmPassword = ko.observable().extend({ mustEqual: self.password() });
    self.company = ko.observable();
    self.availableCountries = ko.observableArray(['Pakistan', 'USA', 'Egypt', 'UAE']);
    self.selectedCountry = ko.observable();
    self.errors = ko.validation.group(self);
  };           
});

,您不再需要require-jquery,因为jQuery defines named AMD module 'jquery' (all lower case) when it detects AMD/RequireJS.

答案 1 :(得分:3)

require.config({
    baseUrl: "/Scripts",
    paths: {
        "Signup": "Signup",
        "knockout": "knockout-2.3.0",
        "knockout.validation": "knockout.validation",
        "jquery": "require-jquery"
    },
    shim: {
        "knockout.validation": {
            "deps": ["knockout"]
        }
    }
});

http://www.requirejs.org/docs/api.html#config-shim