6

I am using require.js with knockout on a website and would like to use the simpleGrid example from this link http://knockoutjs.com/examples/grid.html however I cannot include kncokout.simpleGrid.3.0.js with Require.

I have tried wrapping the plugin with

define(['jQuery', 'knockout'], // Require knockout
    function($, ko) {

   });

This does not work it seems the problem occurs with the templates.

Any help appreciated

PatrickSteele
  • 14,489
  • 2
  • 51
  • 54
danny
  • 1,969
  • 3
  • 16
  • 26

2 Answers2

1

In your require config, you should create a path to the simpleGrid library and use the shim to tell it that it depends on Knockout so that your libraries are loaded in the correct order. Here's an example:

var require = {
    paths: {
        'jquery': 'lib/vendor/jquery-2.0.3',
        'ko': 'lib/vendor/knockout-3.0.0',
        'koSimpleGrid': 'lib/vendor/knockout.simpleGrid.3.0'
    },
    shim: {
        'koSimpleGrid': {
            deps: ['ko']
        },
    }
};

And then you could copy paste the view model code from the example inside of a define like this:

define(['jquery', 'ko', 'koSimpleGrid'], function ($, ko) {
    // VIEW MODEL GOES HERE
});
Simon LeVasseur
  • 412
  • 3
  • 9
0

I agree the problem seems to be with the code that writes the grid template. Essentially, because requirejs loads modules asynchronously, document.write() can't be used - writing of the document has finished by the time a module executes. This StackOverflow answer explains it well I think.

I got round it by instead creating and appending the required script tag templates using dom methods:

templateEngine.addTemplate = function(templateName, templateMarkup) {
  var scriptTag = document.createElement('script');
  scriptTag.type = 'text/html';
  scriptTag.id = templateName;
  scriptTag.text = templateMarkup;
  document.getElementsByTagName('body')[0].appendChild(scriptTag);
};

My amd version is in this gist.

Community
  • 1
  • 1
rogersillito
  • 869
  • 1
  • 10
  • 27