Is it better to use embedded javascript or a separate .js file in an MVC3 view?

Go To StackoverFlow.com

9

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?

2012-04-05 22:29
by Only Bolivian Here
external js files are not just only good for "separation of concerns", we get other main advantages like browser caching, minification etc. so the answer is straight put them in external files - VJAI 2012-04-11 14:02


12

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.

2012-04-05 22:31
by danludwig
Gotta love data attributes - Matthew Blancarte 2012-04-05 22:42


0

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.

2012-04-06 15:57
by Marc Gagne
Ads