danny
danny

Reputation: 2089

Using knockout.simpleGrid.3.0.js with Require.js

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

Upvotes: 6

Views: 974

Answers (2)

rogersillito
rogersillito

Reputation: 941

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.

Upvotes: 0

Simon LeVasseur
Simon LeVasseur

Reputation: 422

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
});

Upvotes: 1

Related Questions