$ (document) .ready () and partial download

I am developing an application using Asp.net mvc and jquery. I would like to use the same naming convention (classes and identifiers) for html elements in different views.

In the case when I want to load a partial view asynchronously, a piece of code $ (document) .ready () in the main view loses its usefulness because none of the html tags patial and css assignment are recognized by jquery. Of course, I do not want to write the same code for each view. What is the best way to solve this problem?

+6
jquery asp.net-mvc partial-views
source share
2 answers

You can use .live() for this, for example:

 $(".myClass").click(function() { }); 

Becomes as follows:

 $(".myClass").live('click', function() { }); 

.live() works differently. .click() bound to the elements selected by the selector when it starts, usually document.ready . .live() works by living in the root of the DOM, listening for events to bubble up and execute a handler if the event that matches the bubbles matches the selector.

+9
source share

I personally just download all the content using my own wrappers around $ .post, and initialize the content if necessary. It also helps to unify error handling, pending notifications, etc.

Third-party libraries usually provide a way to pre-process the content downloaded by ajax.

Partial views will not call document.ready, but they will evaluate scripts inside script tags in the head, so you can force calls with partial views.

Another way I use are custom html tags for forms. For example.

 <form custom-setup="MyCustomSetupFunc"> 

and my $ .post handler checks this tag and calls this function, passing an instance of the form. This helps to narrow the scope of the script during partial loading (useful when multiple instances of a partial file can be loaded on the same page).

0
source share

All Articles