Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 626
Only Bolivian Here Avatar asked Feb 03 '23 06:02

Only Bolivian Here


1 Answers

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.

like image 193
danludwig Avatar answered Feb 05 '23 19:02

danludwig