Using jquery directly in html (and twig) -
short version
normally, include jquery writing xy.js including in html/twig. file uses ready() or maybe load().
are there disadvantages, if use jquery directly in scipt-tag in twig , - in case - call function directly in other script-tag directly in twig-file?
long version
while working on problem (if look...), found out, need basic knowing:
when include jquery via own js-file, can do:
$(document).ready() should used things, when dom loaded - ok
$(document).load() should used, if js depends on resources, may not loaded @ ready()
but what, if include code directly in html (or twig in case). i.e. that:
... {% block subtitlerechts %} {% if app.user %} <span id="add"> <a href="{{ path('add') }}" alt="add item"> <img height="20" src="{{ asset('bundles/mybundle/images/plus.png') }}"></a> </span> <script> $("#add a").each(function() { var url = $("#add a").attr("href"); var $dialog = $('<div class="modalerdialog"></div>'). dialog({ autoopen: false, modal: true, width: 460 }); $(this).click(function() { $dialog.load(url, null, function (responsetext, textstatus, xmlhttprequest) { var title = $('#addpage').attr('title') $dialog.dialog('option', 'title', title); }).dialog('open'); return false; }); }); </script> {% if whatever %} $("#add a").trigger("click"); {% endif %} {% endif %} {% endblock %} ... this should add ajax dialog link in case of 'whatever' directly execute it.
this works local, but don't know, if there disadvantages (beside mixing twig, html js in 1 file). in case, there included js-file
thx in advice.
i guess 1 disadvantage difficulty maintain code. perhaps better solution create model, single flags server-side code this:
//this 1 goes separate .js file function mymodel (){ this.init = function () { $("#add a").each(function() { var url = $("#add a").attr("href"); var $dialog = $('<div class="modalerdialog"></div>'). dialog({ autoopen: false, modal: true, width: 460 }); $(this).click(function() { $dialog.load(url, null, function (responsetext, textstatus, xmlhttprequest) { var title = $('#addpage').attr('title') $dialog.dialog('option', 'title', title); }).dialog('open'); return false; }); }); }(); this.triggerclick = function(boolean) { if(boolean){ $("#add a").trigger("click"); } }; } //this 1 stays on page var model = new mymodel(); model.triggerclick({% whatever %});
Comments
Post a Comment