Domanda

Data questa struttura per un websinte

<html>
  <head>
    <!-- CSS at the beginning-->
    <link/>
  </head>
  <body>
    <div id="mainContainer">
      <div id="side"></div>
      <div id="content">
         <!-- DHTML awesomeness happens here -->
      </div>
    </div>
    <!-- Scripts at the end -->
    <script/>
    <script>
         /* code that attach the JS logic to the HTML items */
    </script>
  </body>
</html>

Utilizzando la normale navigazione web, la pagina rende totalmente in HTML, e seguendo l'approccio progressive enhancement, alla fine cerco alcuni ID o classi specifiche, e io dare loro comportamento dinamico utilizzando JavaScript e jQuery appositamente. Questo codice enhancement accade alla fine del corpo, dopo che gli script esterni è stato scaricato.

In #content, molte interazioni jQuery AJAX accade, alcuni di loro ottenere altri vista parziale dal server e inserirli nella pagina, ma poi devo cercare quei ID e classi di nuovo e allegare oggetti JavaScript per questo nuovi elementi .

Potrebbe essere molto ingombrante, dal momento che non si vuole controllori Riapplicare, gestori di eventi o quant'altro per gli oggetti che hanno già di loro.

Finora, l'unica soluzione che ho trovato è messo nelle mie viste parziali:

@if(Request.IsAjaxRequest())
{
   <script> 
       /* code that attach the JS controllers to the HTML items of this view */
   </script>
}

Credo che un problema simile avviene per esempio quando si vuole $('input.date').datepicker(), e aggiungere nuovi elementi <input type="text" class="date"/> dinamicamente, quelli nuovi non hanno alcuna selezione data a meno che non rexecute la frase jQuery.

Ad esempio, se si considera che in #content ho un <input type="text" class="date"/>:

  1. Al fine di rendere il jQuery datepicer lavoro la prima volta, devo chiamare $('input.date').datepicker() alla fine del <body>, dopo le dichiarazioni <script> esterni.

  2. Se la pagina di download di vista parziale in cui sono nuovi <input type="text" class="date"/> Elementi, devo mettere la chiamata di inizializzazione nella vista di ajax chiamate.

fine Così ho ripetuto con il codice, cosa che io non voglio soprattutto in JS in cui non posso refactoring del codice così facilmente come in C #.

Questa è una cosa che mi sta facendo impazzire la scorsa settimana, chiedendo se c'è un modo migliore per ottenere questo risultato? Una tecnica migliore, o altro approccio complesso?

Come si fa a strutturare le applicazioni web?

Cordiali saluti.

PS: sarebbe bello avere qualcosa di simile .live() o .delegate() ma non solo in relazione con gli eventi, non è vero? Non c'è comunque che jQuery / navigatore solleva ogni volta che si aggiunge qualcosa al DOM?

È stato utile?

Soluzione

This may only be a partial answer to your question, if I understand it correctly.

Regarding your example with <input type="text" class="date" />, we experienced a similar issue with our partial form views that use jQuery unobtrusive validation. When loading them in the browser, we had to call $.validator.unobtrusive.parse('a form selector'); in order to get the validation rules to apply during the next form submission.

If your goal is to avoid repeated code, you could make your js actions unobtrusive, using a pattern like in the jq unobtrusive validation lib. So you would end up with HTML that looks more like this:

<input type="text" class="date" data-datepicker="true" />

You can then put the initialization logic in an unobtrusive parse method.

parse: function(selector) {
    $(selector).find(':input[data-datepicker=true]').each(function() {
        $(this).datepicker();
    }
};

}

This solves your problem of having one place to refactor the code. You can make it start up automatically when the page first loads, and when you load new content via ajax, you can apply the rule to all matching elements by just calling myAppNamespace.unobtrusive.parse('selector for the partial view content');

Update

Take a look at the jquery.validate.unobtrusive.js file in your scripts folder. It really is pretty smart, and if you're not actually extending another jquery plugin (like validate), your code would end up a lot slimmer. If you're looking for full separation of HTML and script, using the HTML5 unobtrusive data- attributes is a good solution imo.

Altri suggerimenti

I have marked the @olivehour response as correct, since it states a good solution for the problem.

What I have finally done, is move the jquery file to the head, and just the jquery file, the rest like "jquery-ui", or custom js files are still in the bottom.

The reason is being able to use $(document).ready or $(function(){}), since using that on the view, the code executes on "onload" or straightaway if the "onload" has been raised already, what is perfect for what I want.

Cheers.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top