Friday, August 30, 2013

Managing Css Files in Durandal 2.0


Durandal does not have a mechanism to manage css file for each view. So I have created a plugin to manage css files.

The plugin is as below. I have placed this plugin under durandal/plugins folder

define(['jquery'], function ($) {
    return {
        loadCss : function (fileName) {
            var cssTag = document.createElement("link")
            cssTag.setAttribute("rel", "stylesheet")
            cssTag.setAttribute("type", "text/css")
            cssTag.setAttribute("href", fileName)
            cssTag.setAttribute("class", "__dynamicCss")

            document.getElementsByTagName("head")[0].appendChild(cssTag)
        },
        removeModuleCss: function () {
            $(".__dynamicCss").remove();

        }
    };
});


In the viewmodel, I have used is as below.

define(['plugins/cssLoader'], function (cssLoader) {
    var ctor = function () {
        this.compositionComplete =  function () {
            cssLoader.loadCss("sample.css");
            cssLoader.loadCss("sample2.css");

            // Recommendation : Use Bundle
        };
        this.deactivate =  function () {
            cssLoader.removeModuleCss();
        }
    };

    return ctor;
});

0 comments: