Is it better to use embedded javascript or a separ

2019-04-06 01:09发布

问题:

I've been told that it's best to place Javascript code in a separate file to keep concerns separated, and while the idea resonates with me, I don't find it practical.

That may just be my inexperience, hence this question.

Here's a clear cut example where I found that placing the code in the View was better than placing it in a separate javascript file.

In my View, I needed to invoke a JQueryUI dialog, and set the title dynamically with the Name of my model.

$("#thumbs img").click(function () {
    var url = $(this).attr("src");
    $(".image-popup").attr("src", url);

    return $("#image-popup").dialog({
        modal: true,
        closeOnEscape: true,
        minHeight: 384,
        minWidth: 596,
        resizable: false,
        show: {
            effect: 'slide',
            duration: 500,
            direction: 'up'
        },
        hide: {
            effect: 'slide',
            duration: 250,
            direction: 'up'
        },
        title: '@Model.Product.Name'
    });
});

Notice:

title: '@Model.Product.Name'

As you can see I have access to the strongly typed model if I use Javascript in my View. This is not the case if I use a separate Javascript file.

Am I doing this wrong, is there something I'm not seeing?

If I were to use a separate file, how would it look like seeing as I can't access the Model properties from within the Javascript file?

回答1:

Separate js file:

<div id="thumbs">
    <img data-dialog-title="@Model.Product.Name" src="[whatever url]" />
</div?

$("#thumbs img").click(function () {
    var title = $(this).data('dialog-title');
    var url = $(this).attr("src");
    $(".image-popup").attr("src", url);

    return $("#image-popup").dialog({
        modal: true,
        closeOnEscape: true,
        minHeight: 384,
        minWidth: 596,
        resizable: false,
        show: {
            effect: 'slide',
            duration: 500,
            direction: 'up'
        },
        hide: {
            effect: 'slide',
            duration: 250,
            direction: 'up'
        },
        title: title
    });
});

Access the model properties unobtrusively through the dom using HTML5 data-* attributes. The javascript above will work perfectly fine as an external file.



回答2:

If you cannot use the aforementioned HTML5 data attributes, then perhaps http://nuget.org/packages/RazorJS will do the trick, seems like it could solve your problem.