running Javascript inside Durandal view

2019-08-16 16:40发布

问题:

I am building a demo to use Durandal to work with D3.js. I modified on the Starter Kit.

It has two views: Welcome and Flickr. I added a new view Chart and copied some d3js visualization javascript code inside my view:

<section>
    chart demo
    <link type="text/css" rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    //more scripts

    <div id="container" style="height: 500px; min-width: 500px"></div>

    <script type="text/javascript">
    d3 visualization code here.     
    </script>

    chart end
</section>

But I find that in a Durandal view, JavaScript code cannot be included. The above code can only display something like:

chart begin
a empty box of size style="height: 500px; min-width: 500px"
chart end

It seems that all the javascirpt code are removed automatically by Durandal.

My question is how to use JavaScript inside a Durandal view? Thanks!

回答1:

You could leverage the viewAttached function of your durandal view model to execute d3 code. Like so:

define(function (require) {
    var vm = {};

    vm.viewAttached = function (view) {
        // d3 visualization code here
        // use class names to find the container instead of id and you can have multiple instances on the same page

        d3.select(view).select(".d3container") 
            .classed("well", true)
            .text('I just styled this div using the magic of D3.');
    };

    return vm;
});