Свой javascript joomla 3

Adding JavaScript

JavaScript (also known as ECMAScript) is a scripting language primarily used in client-side web site development to extend and enhance an end-user’s experience. Joomla provides developers with easy-to-use mechanisms to include JavaScript in their extensions using existing API methods.

There are a number of methods for including JavaScript in your Joomla extensions; some of these are described below.

Contents

Usage

There are three methods for embedding JavaScript into your code using the Joomla API; JDocument::addScriptDeclaration, JDocument::addScript and script. These methods should be called either in your component’s View class (/views//view.html.php) or template script (/views//tmpl/.php or in the case of a module, in its template script (/tmpl/.php).

Inline JavaScript

Blocks of JavaScript code can be declared directly within a component or module’s display template using the JDocument class’ addScriptDeclaration method:

 $document = &JFactory::getDocument(); $document->addScriptDeclaration(' window.event("domready", function() < alert("An inline JavaScript Declaration"); >); '); ?>

External JavaScript

Alternatively, you may wish to separate your JavaScript into a separate file. Separating your JavaScript into an external file can make your template code easier to read especially if the JavaScript is lengthy or complex.

There are two ways to include a JavaScript file using the Joomla API. The first involves using the JDocument class’ addScript method:

 $document = &JFactory::getDocument(); $document->addScript('/media/system/js/sample.js'); ?>

The second uses the JHTML class’ script method:

 // Add the path parameter if the path is different than 'media/system/js/' JHTML::script('sample.js', 'templates/custom/js/'); ?>

Description

The Joomla API’s JDocument::addScriptDeclaration, JDocument::addScript and script methods embed JavaScript into Joomla’s index.php via the jdoc head tag:

Using the JDocument::addScript or script methods to embed JavaScript includes would result in the index.php rendering the following HTML:

head> . script type="text/javaScript" src="/media/system/js/sample.js">/script> . /head>

Calling the class method JDocument::addScriptDeclaration would render the following HTML:

head> . script type="text/javaScript"> window.addEvent("domready", function() < alert("Embedded block of JS here"); >); /script> . /head>

Using these methods is highly recommended as it clearly differentiates another scripting language (JavaScript) from the main PHP code, ensures all JavaScript is correctly embedded between the tags and, in the case of JDocument::addScript and JHTML::script ensures that a JavaScript file is included only once (I.e. there is no .js file duplication).

Using a JavaScript Framework

A Javascript framework provides developers with generic functionality for handling various coding tasks in a familiar, consistent and platform-independent way. A framework enables the developer to forget about the intricacies of implementing a certain function in different web browsers and focus on the requirements of the software.

Two Javascript frameworks are provided as part of Joomla 3.0; JQuery and Mootools. JQuery is a newly introduced framework which integrates with Joomla’s new Bootstrap HTML framework; Mootools is Joomla’s legacy Javascript library which is now superseded by JQuery and is included for backwards compatibility with 3rd party extensions.

In nearly all cases you should use a framework when developing Javascript in your extensions or templates and including one is very simple with Joomla’s API.

JQuery

As of Joomla 3.0 it is highly recommended you use the JQuery framework for all your Javascript as it is loaded by nearly every template which uses the Bootstrap HTML/CSS framework. In those few instances where JQuery is not available, you can easily include the framework using the JHTMLJQuery class’ framework method.

To include the JQuery framework in your extension, you add the following code to your view.html.php or tmpl file:

Using the framework method ensures JQuery is included correctly, only once, and ensures it doesn’t clash with Mootools (if also loaded).

Then it is just a matter of leveraging the JQuery framework:

JFactory::getDocument()->addScriptDeclaration(' (function($) < $(document).ready(function() < alert($("#list li").size()); >); >)(jQuery); ');

More information about JQuery is available at http://docs.jquery.com/How_jQuery_Works. For API documentation, visit http://docs.jquery.com/.

Mootools

Unless you are maintaining Javascript code which leverages Mootools or you are developing an extension for a Joomla version prior to 3.0 it is recommended you use JQuery instead.

Firstly, you will need to include the Mootools code in your extension. To include the Mootools framework in your extension, you add the following code to your view.html.php or tmpl file:

The above code results in the same outcome as the similar JQuery framework statement; that is it ensures Mootools is included correctly and only once.

Then using Mootools is almost identical to JQuery:

JFactory::getDocument()->addScriptDeclaration(' window.addEvent("domready", function() < alert($("list").getElements("li").length); >); ');

More information about Mootools is available at http://mootools.net/. For API documentation, visit http://mootools.net/docs/core.

See Also

JHtmlBehaviour::framework method from the Joomla! Framework 11.1 documentation

Источник

Подключение Javascript-фреймворков в Joomla 3

Это также автоматически подключит фреймворк jQuery в режиме no conflict. Это означает, что работа должна осуществляться через пространство имен jQuery , а не через $ . Подключаемая версия библиотеки Bootstrap 2.3.2, и она расположена в /media/jui/js/bootstrap.js . Включает в себя методы для инициализации следующих плагинов: alert, button, carousel, collapse, dropdown, modal, tooltip, popover, scrollspy, tab, typeahead и affix. Подробнее об использовании Boostrap в Joomla 3 в статье «Bootstrap JHtml библиотека для Joomla 3.0».

Примечание: существует известная несовместимость между bootstrap-button и jquery-ui-button . Использование обоих кнопок на одной и той же странице приведет к конфликту.

jQuery

Для того чтобы подключить jQuery, используйте:

Это загрузит библиотеку jQuery версии 1.10.2 в режиме no conflict. Для загрузки в нормальном режиме, используйте:

JHtml::_('jquery.framework', false);

jQuery UI

Библиотека JUX (Joomla User Experience) включает в себя ядро jQuery UI Core (версия 1.9.2 на момент Joomla 3.2.1) плюс Widget, Mouse, Position, а также плагин Sortable. Документацию по использованию вы можете найти на странице jQuery UI. Для загрузки ядра используйте:

Это загрузит jquery-ui.core.js из директории /media/jui/js/ . Включение jQuery UI автоматически включает JQuery в режиме no conflict, если это не было сделано ранее.

Для добавления библиотеки Sortable используйте:

JHtml::_('jquery.ui', array('sortable'));

Это автоматически загрузит ядро jQuery UI и библиотеку jQuery. Для прозрачности кода, лучше всего подключать эти две библиотеки через один вызов:

JHtml::_('jquery.ui', array('core', 'sortable'));

MooTools

Предполагается, что этот фреймворк будет исключен из будущих версий Joomla.

JHtml::_('behavior.framework', $type)

Где $type определяет тип (по умолчанию core). Загружает библиотеку MooTools из /media/system/js . Core: mootools-core.js, версия 1.4.5. More: mootools-more.js, версия 1.4.0.1. Подключение more автоматически включает core.

Joomla! Javascript Framework

Множество библиотек Joomla требуют фреймворк MooTools. Предполагается, что они будут мигрированы в фреймворк Bootstrap в будущих версиях Joomla.

Эти javascript библиотеки расположены в папке /media/system/js . Вот некоторые из них:

JHtml::_('behavior.caption', $selector)

Применит функцию подписи (caption) ко всем элементам с классом $selector . По умолчанию классом селектора является img.caption . Для того чтобы применить его к нескольким классам просто вызовите JHtml::_(‘behavior.caption’, $selector) несколько раз. Библиотека загрузится единожды, но будет применена ко всем указанным классам.

JHtml::_('behavior.tooltip', $selector, $params)

Для всех DOM объектов с классом $selector будет создан onhover тултип с необходимыми параметрами $params . По умолчанию классом селектора является ‘hasTip’ . Подключение этой библиотеки загрузит фреймворк MooTools.

Создает эффект combobox (поле со списком). Подключение этой библиотеки загрузит фреймворк MooTools.

JHtml::_('behavior.formvalidation')

Включает валидацию формы, которая основана на правилах, которые определены полями формы. Подключение этой библиотеки загрузит фреймворк MooTools.

Плагины для фреймворков и собственные библиотеки

Для подключения сторонних плагинов и/или своих библиотек используйте JHtml::_(‘script’) с необходимыми параметрами. Например:

JHtml::_('jquery.ui'); JHtml::script('com_mycomp/jqueryplugin.js', false, true);

Это подключит библиотеку jQuery (если она не была подключена ранее) и файл /media/com_mycomp/js/jqueryplugin.js . Хорошей практикой считается использовать папку media для расположения скриптов. Подробнее об этом вы можете прочитать в статье «Используйте папку media для разрешения переопределения медиаданных».

Источник

Читайте также:  Sign Up
Оцените статью