views:

94

answers:

3

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.

A: 

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

zihotki
A: 

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 */ }
Lachlan Roche
+1  A: 

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.

Brian
Brian, thanks. We have also created several jquery plugins to encapsulate reusable code and they work really well. However, in this particular case, mostly the view is referencing functions from the partial, so callback functions would not be appropriate. But we may go down the jQuery plugin route at the end.
Hey, if the partial uses a class or JQUery plugin structure, the view could check for the existence of those objects by doing a type check, and call it explicitly, thereby ensuring that the correct objects exist and are being called. This would work well if you use AJAX or JQuery to do AJAX postbacks too. If you would like any more help, adding some sample code would help us to advise further.
Brian