Search code examples
knockout.jsrequirejsjquery-select2amd

requirejs w/ knockoutjs w/ select2 fails to update observable on first load


The first time that we load the requirejs module the observables from my view model seems not to being updated. But when you comment $("#ddl").select2(); everything works fine.

requirejs.config({
    'paths': {
        'jquery': '//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.0.min',
            'ko': '//ajax.aspnetcdn.com/ajax/knockout/knockout-3.0.0',
            'select2': '//ivaynberg.github.io/select2/select2-3.4.5/select2',
            'domReady': 
                '//cdnjs.cloudflare.com/ajax/libs/require-domReady/2.0.1/domReady'
    },
        'shim': {
        'select2': {
            deps: ['jquery'],
            exports: '$.select2'
        }
    }
});

define('simpleKo', ['jquery', 'ko', 'domReady', 'select2'],

function ($, ko, domReady) {
    var simpleViewModel = function () {
        var self = this;
        self.name = ko.observable();
        self.names = ko.observableArray(['John', 'Tim', 'Mike', 'Jay']);
    };

    domReady(function () {
        ko.applyBindings(new simpleViewModel());
        $("#ddl").select2({
            width: 'resolve'
        });
    });
});

requirejs(['simpleKo']);

There is a live exemple on JSFiddle that fails when you first open the link without cache.

I've already tried everything, anyone have ideas to what may be happening?


Solution

  • A much easier way is tell to RequireJS that KnockoutJS depends of select2, even though it's not truth.

            'shim': {
                'select2': {
                    deps: ['jquery'],
                    exports: '$.select2'
                },
                'ko' : {
                    deps: ['select2']
                }
             }