running Javascript inside Durandal view

五迷三道 提交于 2019-12-11 19:44:58

问题


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


来源:https://stackoverflow.com/questions/17640856/running-javascript-inside-durandal-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!