Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...