I started removing part of a view into a partial so that it could be reused on another view. However, I got stuck because there are some JavaScript functions on the original view that call some of the functions that belong to the partial. It seems wrong to call functions that are defined on the partial from the containing view (and vice-versa). What is the best practice for this situation? Thanks.
I recommend you to use some ScriptManager and move all js functionality to external files so you'll need just to register required file for this partial in the partial view. See these links for details:
http://stackoverflow.com/questions/320333/scriptmanager-asp-net-mvc
http://mvcscriptmanager.codeplex.com/
http://www.telerik.com/help/aspnet-mvc/web-assets-working-with-javascript-web-assets.html
If the view may optionally contain the partial, it can test for the existence of a function before calling it:
if (typeof(foo) == 'function') {
foo();
}
Or the view could define a default version of the function, which may be overridden by the partial.
// in view or master
function foo() {}
// then in the partial
function foo() { /* does something */ }
Hey,
I created an app myself and ran into this, though I didn't implement it yet, I plan to leverage JQuery plugins to do a lot of this. You can't embed the JS in the partial view if you load the partial via AJAX because it won't run.
JQuery is a very nice framework and easy to build plugins. You just have to start designing your JS so that it's more reusable (not hard-coding element references and such).
Alternatively, without JQuery, create separate JS files and design your code using JS classes is a good strategy too.
HTH.