knockout.observableDictionary
knockout.observableDictionary copied to clipboard
How to load with requirejs?
My project uses requirejs to manage dependencies, and when I set up the config for knockout and then observableDictionary, I get a "ko is not defined" error, I think because your code is expecting ko to be in the global scope. My config looks like this:
requirejs.config({
paths: {
'knockout': '../Scripts/knockout-2.3.0',
'observableDictionary': '../Scripts/observableDictionary'
},
shim: {
'observableDictionary': {
deps: ['knockout'],
exports: 'observableDictionary'
}
}
});
The only solution I have at the moment is to wrap your code in a define
block, but that's obviously not a good long-term solution. I'm pretty new to requirejs so it's entirely possible that I'm missing something. Any insight you might have would be great. Thanks!
Did you ever get an answer to this?
This is for future readers:
Replace the current header
(function () {
function DictionaryItem(key, value, dictionary) {
with:
(function (factory) {
// CommonJS
if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
factory(require('knockout'));
// AMD
} else if (typeof define === 'function' && define.amd) {
define(['knockout'], factory);
// Normal script tag
} else {
factory(window.ko);
}
}(function (ko) {
function DictionaryItem(key, value, dictionary) {
then in your requirejs.config:
'knockout-dictionary' : './path/to/file',
...
// App bootstrap code
define(['knockout-dictionary'], function () {
...
})
Requirejs will load in the file. It has a dependency to knockout, which is a singleton across the whole appplication. That singleton will receive the observableDictionary method and it will be available across the whole application