Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

knockout.js - how to stop durandal / jquery stripping out script tags from views?

I know there are better patterns but in this case there's some legacy code that we'd like to move to a view. This html has a

<script src="binding.js"></script>

that needs to run after the page renders and displays.

I hoped to do this with a <script src=""> tag, but the tag seems to be getting stripped out.

How do we either get the script tag to render, or do a work-around with durandal?

Example html:

<div>
    <link rel="stylesheet" href="/Content/stylesheet1.css"/>
    <link rel="stylesheet" href="/Content/stylesheet2.css"/>
    <header>
        <h1>heading</h1>
        <h2>sub heading</h2>
    </header>

    <section>
    </section>

    <footer>              
    </footer>
    <script src="dobinding.js"></script>    
</div>

This is helpful:

http://knockoutjs.com/documentation/custom-bindings.html
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use a custom KnockOut binding for this.

Here's a really simple binding - keep in mind this is just an idea:

ko.bindingHandlers.script = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var scriptName = ko.utils.unwrapObservable(valueAccessor());
        $(element).html("<script src='" + scriptName + "'></script>");
    }
};

In your view (.html file):

<div data-bind="script:'dobinding.js'"></div>

I tested this, and I found that the script is indeed injected, parsed, and executed, but it doesn't stay loaded in the DOM. That may or may not be an issue for you.

Seems that stripping the tags may be a Durandal-specific thing. I haven't figured out the cause yet, but I'll update if I get a chance to dig into it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...