Что я сделал, так это создал объект js, используя шаблон вызова метода, затем вы можете вызвать его из внешнего файла js. Поскольку js использует глобальные переменные, я инкапсулирую их, чтобы не было конфликтов с другими библиотеками js.
Пример:
По мнению
@section scripts{
<script>
var thisPage = {
variableOne: '@Model.One',
someAjaxUrl: function () { return '@Url.Action("ActionName", "ControllerName")'; }
};
</script>
@Scripts.Render("~/Scripts/PathToExternalScriptFile.js")
}
Теперь внутри внешней страницы вы можете получить данные в защищенной области, чтобы они не конфликтовали с другими глобальными переменными в js.
console.log('VariableOne = ' + thisPage.variableOne);
console.log('Some URL = ' + thisPage.someAjaxUrl());
Также вы можете обернуть его внутри модуля во внешнем файле, чтобы сделать его еще более надежным.
Пример:
$(function () {
MyHelperModule.init(thisPage || {});
});
var MyHelperModule = (function () {
var _helperName = 'MyHelperModule';
// default values
var _settings = { debug: false, timeout:10000, intervalRate:60000};
//initialize the module
var _init = function (settings) {
// combine/replace with (thisPage/settings) passed in
_settings = $.extend(_settings, settings);
// will only display if thisPage has a debug var set to true
_write('*** DEBUGGER ENABLED ***');
// do some setup stuff
// Example to set up interval
setInterval(
function () { _someCheck(); }
, _settings.intervalRate
);
return this; // allow for chaining of calls to helper
};
// sends info to console for module
var _write = function (text, always) {
if (always !== undefined && always === true || _settings.debug === true) {
console.log(moment(new Date()).format() + ' ~ ' + _helperName + ': ' + text);
}
};
// makes the request
var _someCheck = function () {
// if needed values are in settings
if (typeof _settings.someAjaxUrl === 'function'
&& _settings.variableOne !== undefined) {
$.ajax({
dataType: 'json'
, url: _settings.someAjaxUrl()
, data: {
varOne: _settings.variableOne
}
, timeout: _settings.timeout
}).done(function (data) {
// do stuff
_write('Done');
}).fail(function (jqxhr, textStatus, error) {
_write('Fail: [' + jqxhr.status + ']', true);
}).always(function () {
_write('Always');
});
} else {// if any of the page settings don't exist
_write('The module settings do not hold all required variables....', true);
}
};
// Public calls
return {
init: _init
};
})();