它是更好地使用嵌入的JavaScript或单独的.js文件在MVC3看法? [英] Is it better to use embedded javascript or a separate .js file in an MVC3 view?
问题描述
有人告诉我说,最好将JavaScript code在一个单独的文件,以保持分离的担忧,虽然这个想法与我产生共鸣,我并不觉得踏实。
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.
下面是一个明确的例子,我发现,放置code的看法是不是将其放置在一个单独的JavaScript文件更好。
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.
在我看来,我需要调用jQueryUI的对话框,并与我的模型的名称动态设置标题。
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'
});
});
注意:
title: '@Model.Product.Name'
正如你可以看到我有的访问的到,如果我在我看来,使用JavaScript的强类型的模型。这是不是这样,如果我使用一个单独的JavaScript文件。
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?
如果我是用一个单独的文件,怎么会看起来像看到,因为我无法从JavaScript内提交访问模型属性?
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?
推荐答案
独立的js文件:
<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
});
});
使用HTML5数据 - *属性悄悄地通过访问DOM模型属性。上面的JavaScript将完全正常工作作为外部文件。
Access the model properties unobtrusively through the dom using HTML5 data-* attributes. The javascript above will work perfectly fine as an external file.
这篇关于它是更好地使用嵌入的JavaScript或单独的.js文件在MVC3看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!