/ Gists

Gists

On gists

Formulář jako objekt - můj výtvor

JavaScript-OOP JavaScript

formjs-object-my.js #


	(function() {
 
		var Form = {
			init: function(config) 
			{
				this.form            = config.form;
				this.mandatoryFields = this.form.find('input[name="name"], input[name="phone"], input[name="email"], input[name="date"], input[name="time"], input[name="persons"]');
				this.url             = this.form.attr('action');
				this.submitButton    = this.form.find('button');
				this.binds();
			},

			binds: function()
			{
				var self = this;
				this.submitButton.on('click', function(e){
					e.preventDefault();
					var formData = self.form.serialize();
					self.dispatch(formData);
				});
			},
			formFieldCleaner(formObject)
			{ 
				$(":input", formObject).not(":button, :submit, :reset, :hidden")
									   .val("")
									   .removeAttr("checked")
									   .removeAttr("selected"); 
			},
			showErrors: function(error)
			{
				var self = this;

				this.mandatoryFields.removeClass('-error');
				$('#form-message-success').html('')
										  .hide();
										  
				$('#form-message-error').show()
										.html(error.msg.join('<br />'));

				$.each(error.missingField, function(){

					self.form.find('input[name="'+this+'"]')
					              .addClass('-error');
				});
			

			},
			showSuccess: function(msg)
			{
				this.mandatoryFields.removeClass('-error');	
				this.formFieldCleaner(this.form);
				$('#form-message-error').html('')
										.hide();
										
				$('#form-message-success').show()
										  .html(msg)
										  .delay(5000)
										  .fadeOut(800);
			},
			dispatch: function(formData) 
			{
		
				
				var self = this;
				var xhr = $.post(this.url, formData);

				xhr.done(function(json){
					
					json = JSON.parse(json);

					// chyba
					if (json.error.state)
					{
						self.showErrors(json.error);
					}
					else
					{
						self.showSuccess(json.success.message);
					}


				});
			}
		};

		Form.init({
			form: $('#reservation-form')
		});

		})();

On gists

Styleswitcher

jQuery jQuery-plugins

styleswitcher.js #

jQuery.fn.styleSwitcher = function(){
    $(this).click(function(){
        loadStyleSheet(this);
        return false;
    });
    function loadStyleSheet(obj) {
        $('body').append('<div id="overlay" />');
        $('body').css({height:'100%'});
        $('#overlay')
            .css({
                display: 'none',
                position: 'absolute',
                top:0,
                left: 0,
                width: '100%',
                height: '100%',
                zIndex: 1000,
                background: 'black url(img/loading.gif) no-repeat center'
            })
            .fadeIn(500,function(){
                $.get( obj.href+'&js',function(data){
                    $('#stylesheet').attr('href','css/' + data + '.css');
                    cssDummy.check(function(){
                        $('#overlay').fadeOut(500,function(){
                            $(this).remove();
                        });
                    });
                });
            });
    }
    var cssDummy = {
        init: function(){
            $('<div id="dummy-element" style="display:none" />').appendTo('body');
        },
        check: function(callback) {
            if ($('#dummy-element').width()==2) callback();
            else setTimeout(function(){cssDummy.check(callback)}, 200);
        }
    }
    cssDummy.init();
}

On gists

Template config

AW

settings.ini #

template=default-variable
[placeholders]
headline=Nadpis
text=Text#Html
[templateConfig]
headlineTag = h4

On gists

jQuery plugin pattern

Plugin patterns jQuery jQuery-plugins

pattern.js #

;(function($) {
    var privateFunction = function () {
        //do something
    }

    var methods = {
        init : function( options ) {

            var defaults = {
                center: {
                    lat: -36.8442,
                    lng: 174.7676
                }
             };
             var t = $.extend(true, defaults, options);

             return this.each(function () {
                 var $this = $(this),
                 data = $this.data('myMapPlugin');

                 if ( !data ) {

                     var map = new google.maps.Map(this, {
                         zoom: 8,
                         center: new google.maps.LatLng(t['center'][lat], t['center']['lng']),
                         mapTypeId: google.maps.MapTypeId.ROADMAP,
                         mapTypeControlOptions:{
                             mapTypeIds: [google.maps.MapTypeId.ROADMAP]
                         }
                     });

                     var geocoder  = new google.maps.Geocoder();

                     var $form = $('form', $this.parent());
                     var form = $form.get(0);
                     var $search = $('input[data-type=search]', $form);

                     $form.submit(function () {
                         $this.myMapPlugin('search', $search.val());
                         return false;
                     });

                     google.maps.event.addListener(map, 'idle', function () {
                         // do something
                     });

                     $this.data('myMapPlugin', {
                         'target': $this,
                         'map': map,
                         'form':form,
                         'geocoder':geocoder
                     });
                 }
             });
         },
         resize : function ( ) {
             return this.each(function(){
                 var $this = $(this),
                     data = $this.data('myMapPlugin');

                 google.maps.event.trigger(data.map, 'resize');
             });
         },
         search : function ( searchString ) {
             return this.each(function () {
             // do something with geocoder              
             });
         },
         update : function ( content ) {
             // ToDo
         },
         destroy : function ( ) {
             return this.each(function(){

                 var $this = $(this),
                 data = $this.data('myMapPlugin');

                 $(window).unbind('.locationmap');
                 data.locationmap.remove();
                 $this.removeData('locationmap');
             });
        }
    };


    $.fn.myMapPlugin = function (method) {
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.myMapPlugin' );
        }
   };
})(jQuery);

On gists

Is element in viewport?

JavaScript Helpers-Filters-Plugins

is-in-viewport.js #

/**
 * Check if DOM element is in browsers view port
 * @param el The element
 * @return boolean
 */
function isInViewport(el) {
    var rect = el.getBoundingClientRect();

    return (
        rect.bottom >= 0 &&
        rect.right >= 0 &&

        rect.top <= (
            window.innerHeight ||
            document.documentElement.clientHeight) &&

        rect.left <= (
            window.innerWidth ||
            document.documentElement.clientWidth)
    );
}

On gists

SignForm Factory

Nette-Forms

form-factory.php #


<?php

declare(strict_types=1);
namespace App\Forms;
use Nette;
use Nette\Application\UI\Form;
use Nette\Security\User;
final class SignInFormFactory
{
	use Nette\SmartObject;
	/** @var FormFactory */
	private $factory;
	/** @var User */
	private $user;
	public function __construct(FormFactory $factory, User $user)
	{
		$this->factory = $factory;
		$this->user = $user;
	}
	public function create(callable $onSuccess): Form
	{
		$form = $this->factory->create();
		$form->addText('username', 'Username:')
			->setRequired('Please enter your username.');
		$form->addPassword('password', 'Password:')
			->setRequired('Please enter your password.');
		$form->addCheckbox('remember', 'Keep me signed in');
		$form->addSubmit('send', 'Sign in');
		$form->onSuccess[] = function (Form $form, \stdClass $values) use ($onSuccess): void {
			try {
				$this->user->setExpiration($values->remember ? '14 days' : '20 minutes');
				$this->user->login($values->username, $values->password);
			} catch (Nette\Security\AuthenticationException $e) {
				$form->addError('The username or password you entered is incorrect.');
				return;
			}
			$onSuccess();
		};
		return $form;
	}

On gists

SignForm Factory

Nette Nette-Forms

form-factory.php #


<?php

declare(strict_types=1);
namespace App\Forms;
use Nette;
use Nette\Application\UI\Form;
use Nette\Security\User;
final class SignInFormFactory
{
	use Nette\SmartObject;
	/** @var FormFactory */
	private $factory;
	/** @var User */
	private $user;
	public function __construct(FormFactory $factory, User $user)
	{
		$this->factory = $factory;
		$this->user = $user;
	}
	public function create(callable $onSuccess): Form
	{
		$form = $this->factory->create();
		$form->addText('username', 'Username:')
			->setRequired('Please enter your username.');
		$form->addPassword('password', 'Password:')
			->setRequired('Please enter your password.');
		$form->addCheckbox('remember', 'Keep me signed in');
		$form->addSubmit('send', 'Sign in');
		$form->onSuccess[] = function (Form $form, \stdClass $values) use ($onSuccess): void {
			try {
				$this->user->setExpiration($values->remember ? '14 days' : '20 minutes');
				$this->user->login($values->username, $values->password);
			} catch (Nette\Security\AuthenticationException $e) {
				$form->addError('The username or password you entered is incorrect.');
				return;
			}
			$onSuccess();
		};
		return $form;
	}

On gists

Postupné renderování inputu / Partial rendering of input element

Nette Nette-Forms Nette-Tricks

partial-rendering.latte #

<div class="col-12">
    {!$form['agreement']->getOneLabel('basic')->startTag()}
        {$form['agreement']->getOneControl('basic')}
        {!_'Souhlasím zpracování'}
    {!$form['agreement']->getOneLabel('basic')->endTag()}
</div>

<div class="cl"></div>
<div class="h15"></div>

<div class="col-12">
    {!$form['agreement']->getOneLabel('full')->startTag()}
        {$form['agreement']->getOneControl('full')}
        {!_'Nesouhlasím zpracování'}
     {!$form['agreement']->getOneLabel('full')->endTag()}
</div>

On gists

Připojení komponenty na určité místo do stromu

Nette Nette-Forms

add-component.php #

<?php

		$form->addComponent(
		new Nette\Forms\Controls\TextInput('Firma'),
		'billing_name',
		'billing_firstname' // insertBefore arg
	   );

On gists

Anonymous self invoke functions

PHP Helpers-Filters-Plugins

anonymous.php #

<?php

call_user_func(function() { 
  
  // your code here ...

});