Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Friday, December 5, 2014

client side reorder list

I am looking into jquery ui drag and drop grid row

http://jqueryui.com/sortable/

Enable a group of DOM elements to be sortable. Click on and drag an element to a new spot within the list, and the other items will adjust to fit. By default, sortable items share draggable properties

http://api.jqueryui.com/sortable/

options:
items: Specifies which items inside the element should be sortable
handle:Restricts sort start click to the specified element.

events:
stop( event, ui )Type: sortstop This event is triggered when sorting has stopped


example : http://plnkr.co/edit/jpxc42tF55jktfI3upTE?p=preview 














Tuesday, November 18, 2014

Links i have learned about lately


https://github.com/gregturn/spring-a-gram - Spring Boot, Spring Data, Spring Rest and JQuery UI (see GalleryRepository class , PagingAndSortingRepository)

Nodevember
- http://nodevember.org/#speakers
- http://nodevember.org/#speakers

Angular sub topics

A few weeks ago I used angular to create a sample app.  That was a good experience. In keeping with learning more Angular,  I came a cross a podcast blog Adventures in Angular. The first episode i listened to was http://devchat.tv/adventures-in-angular/angular-meetups-with-matt-zabriskie-and-sharon-diorio . This talk had training videos sessions:

Meetup Angular and bootstrap - see Plunkr
Utah Angular user group
Testing with Angular

Pluralsight has training on bootstrap 3 as well.

Saturday, November 1, 2014

DevFest at American Underground 2014

The Dev Fest is organized by  Luke Dary  +Luke Dary .  Next GDG meeting possibly will  be held in the Google office in Chapel Hill. Udacity will be partnering to do Android development course thru GDG.

Polymer  #itshackademic

polymer-project.org

Intro Video

Rob Dodson - Core Icons

what problems solving?   css is global , phone/tablets,smart tvs  etc  Front end development so it works on all devices. i.e Tabs should be easy, not easy to plop in anywhere. old frameworks can be a challenge,

<paper-tabs>
<paper-tab>one</paper-tab>

tip: do a  view source of gmail
table soup, div soup
web components
-  required to have dash in name to be custom element (otherwise show as unknown)
- paper tab (material design )
- resusable
-  templates -native client side  , parsed, does not render, content inert til cloned/used,
- shadow dom - browser not rendering all, chrome has ability to show hidden structure you dont usually see
- html imports <link rel="import" href="bootstrap.html">      vulcanize - tool to concat your dependencies and do it once
- custom elements : use existing, extend others, encapsulated css customelements.io


http://itshackademic.com/

https://www.polymer-project.org/docs/start/getting-the-code.html


https://www.polymer-project.org/docs/start/creatingelements.html


Thursday, October 30, 2014

Next Web

I recently watched Eric Bidelman's talk from Google I/O 2013 on Web Components.  This talk was on the Future of the web platform. This talk reminds me of Angular methodology where you are adding custom tags to HTML.

As well  Peter Gasston talks about web components and CSS. Example of video player which runs on javascript, html, css.  If you show hidden dom, you can see markup.

Show shadow dom in web tools under wrench:





shadow root, host, dom

shadow root:
var newroot  = $(foo).createShadowRoot(), newElem =  '<h2<test</h2>' ;

newroot.innerHTML = newElem ;

<div id ="foo"><h1> First</h1></div>

div tag  is the shadow host, and h1 text replaces h2 with test.


widget example: <div id ="foo"><h1> First</h1></div>
want it but in different color
encapsulation - has all it needs contains within itslef, nothing gets in, nothing gets out
encapsulation in html is iframe today - issues extra network, multiplee rendering, cross orgin conflicts
better encapsulation is web components
reusable web components - shadowdom, templates,  custom tags

templates - put stuff in it

<template id ="foo"><h2> First</h2></template>
<div id ="bar"><h1>text 2</h1></div>

mark up inside is inert - does nothing, does not get loaded

inside template known as content

var test = $(foo).content.cloneNode(true), bar = document.getElementById('bar');
bar.appendChild(test);

puts template inside bar div tag  - template active

share templates across multiple files using import



4 main areas (Shadow DOM gives encapsulation, templates or chunk of markup that later you can stamp out your elements, custom tags, html imports that can be reused via CDN URLs):



HTML templates:
Template out your markup 
Put dom in it
Parsed not rendered - won't run until you stamp it out, same for media
Hidden from document, cant traverse into,  its in its own context

Content property - document fragment , clone it, stamp it out, see whats in it

Example:


Clone it is what stamps it out (here it runs script when that happens):

http://www.webcomponentsshift.com/#15

New spec for html templates  : chrome supports it.


Shadow dom (Secret markup in elements):
markup encapsulation, DOM encapsulation, css style boundary protection, no bleeding in, style boundaries, exposes to developers mechanics browser vendors use to create their html elements

iframe has it but bloated, hard to use  (extra network requests needed, multiple rendering contexts)




Dom nodes can host hidden dom

hidden dom  can't be accessed by outside  javscript





Hidden document fragment

Using markup to control it

Browser vendors been holding out

http://www.webcomponentsshift.com/#23



Filled in markup

Shadow dom gets rendered


Style things

This time add styling make it red



@host

Host element provide default styles






Custom elements (require hyphen)

Ability to define new elements

Plunkr example 






Using js html.prototype 

http://www.webcomponentsshift.com/#35



Html imports




Saturday, October 11, 2014

Just took a Bower

Tool for easily manage the 3rd party client side libraries within your code.

The old school process is to browse, download, extract zip, find files, copy, links to files in html.

Bower eliminates most of this Its for client side files, but can do any type of files. Bower calls the files modules Packages

Bower calls into Github to get files

 npm install -g bower

 bowser install <proj>

 Dist directory js and minified one

 Add it to your project in script tag

 Get rid of something
   bower uninstall <proj>

 Updating projects (i.e. multiple)

bower update

Might need to be careful

One at a time

bower install <proj>

What packages?

bower list

bower search <proj>

http://bower.io/search/

bower.json file
- name,  version, main, dependencies

bower init
- prompted to create json file

.bowerrc
- directory:relative path to folder

bower install
bower install <project> --save
bower uninstall <project> --save


Related post : [http://bloomonclientside.blogspot.com/2013/11/bower-is-package-manager-for-installing.html]

Tuesday, September 30, 2014

Polymer

Polymer approach:
Elements are pretty great. They’re the building blocks of the web. Unfortunately, as web apps got more complex, we collectively outgrew the basic set of elements that ships in browsers. Our solution was to replace markup with gobs of script. In that shift, we’ve lost the elegance of the element. Polymer returns to our roots. We think the answer is not gobs of script, but rather to build more powerful elements. A set of powerful new technologies called Web Components makes this possible.

Custom Elements:
Embracing the philosophy means a web app becomes a collection of well-defined, reusable components.




Using Elements



Creating Elements

https://www.youtube.com/watch?v=5b5O5cclPbk (web components overview)

- https://github.com/KamiQuasi/wc-overview
- natively without polyfills



Intro Polymer
- easier to create custom elements
- quiz application demo app w paper elements
- inimation 60 frames / sec

https://www.youtube.com/watch?v=3CJcHJGZfws (web components and polymer overview)



http://www.polymer-project.org/resources/video.html




http://www.polymer-project.org/docs/start/tutorial/intro.html
http://www.html5rocks.com/en/tutorials/webcomponents/template/
https://www.youtube.com/watch?v=eJZx9c6YL8k
http://www.polymer-project.org/docs/polymer/polymer.html#altregistration
http://www.polymer-project.org/docs/polymer/databinding.html
http://www.polymer-project.org/docs/polymer/databinding-advanced.html#autobinding

https://github.com/Polymer/observe-js

Thursday, September 25, 2014

Web Components 101

I recently watched Eric Bidelman's talk from Google I/O 2013 on Web Components.  This talk was on the Future of the web platform. This talk reminds me of Angular methodology where you are adding custom tags to HTML.

4 main areas (Shadow DOM gives encapsulation, templates or chunk of markup that later you can stamp out your elements, custom tags, html imports that can be reused via CDN URLs):











HTML templates:
Template out your markup 
Put dom in it
Parsed not rendered - won't run until you stamp it out, same for media
Hidden from document, cant traverse into,  its in its own context

Content property - document fragment , clone it, stamp it out, see whats in it

Example:


Clone it is what stamps it out (here it runs script when that happens):











New spec for html templates  : chrome supports it.




Shadow dom (Secret markup in elements):
markup encapsulation, DOM encapsulation, css style boundary protection, no bleeding in, style boundaries, exposes to developers mechanics browser vendors use to create their html elements

iframe has it but bloated, hard to use  (extra network requests needed, multiple rendering contexts)











Dom nodes can host hidden dom

hidden dom  can't be accessed by outside  javscript


Show shadow dom in web tools under wrench:







Hidden document fragment

Using markup to control it

Browser vendors been holding out
















Filled in markup

Shadow dom gets rendered


Style things

This time add styling make it red











@host

Host element provide default styles




















Custom elements (require hyphen)

Ability to define new elements

Plunkr example 





















































Using js html.prototype 

























































Html imports
































Tuesday, September 23, 2014

Plunker


http://plnkr.co/

Launch the editor





On right side in the initial display (or click on second button down on the right that looks like a book), you can add external libraries into your javascript. Either search for a library or click the button of an an already displayed library.

Note that the top icon on right is to preview on the right the generated output.

You can click the save button on top left to save your script to a generated web URL.

Double click a file name on left to rename it, click x icon to delete a file , or click the add file hyperlink to add a file.

There is preview button on right for a large  display of the displayed output.

Check mark button on the right is for lint integration.

Th gear icon is personal seetings like font and auto-refresh which runs the script again at interval selected . Or turn auto-refresh off.


Dev tools invocation will show you any JavaScript errors in console tab.

Right click on console and click options to clear console

To debug go in the sources tab.

ctrl-o to open your js file by entering file name in the input box.

debugging resume f8

Tuesday, June 10, 2014

Javascript hoistology



Scope and Hoisting explained
  • Unlike most programming languages, JavaScript does not have block-level scope
  • Variables have either a local scope or a global scope.
  • If you don't declare your local variables with the var keyword, they are part of the global scope
  • All variables declared outside a function are in the global scope. In the browser, which is what we are concerned with as front-end developers, the global context or scope is the window object
  • a variable is initialized (assigned a value) without first being declared with the var keyword, it is automatically added to the global context and it is thus a global variable
Only functions create new scope
http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

JavaScript Declarations are Hoisted - variable used before its declared. JavaScript Initializations are Not Hoisted -  http://www.w3schools.com/js/tryit.asp?filename=tryjs_hoisting1


http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/
If a value is enumerable, it will show up when enumerating over an object using a for(prop in obj) loop. If a property is writable, you can replace it. If a property is configurable, you can delete it or change its other attributes. 
var person = Object.create(null); 
Object.defineProperty(person, 'firstName', { value: "Yehuda", writable: true, enumerable: true, configurable: true });



hasownproperty-vs-propertyisenumerable
The propertyIsEnumerable method returns true if proName exists in object and can be enumerated using a ForIn loop. The propertyIsEnumerable method returns false if object does not have a property of the specified name or if the specified property is not enumerable. Typically, predefined properties are not enumerable while user-defined properties are always enumerable. The hasOwnProperty method returns true if object has a property of the specified name, false if it does not. This method does not check if the property exists in the object's prototype chain; the property must be a member of the object itself.

Every function has these methods you can call (Object.getOwnPropertyNames(Function.prototype)):
  • toString
  • call
  • apply
  • length
  • name
  • arguments
  • caller
  • constructor
  • bind

http://www.codelord.net/2014/03/14/please-use-hasownproperty-short-story-of-a-hack/



http://www.akhildeshpande.com/2012/09/javascript-prototype.html#more


Friday, June 6, 2014

Javascript this and call that

The essentials video on 'this' says: " this refers to owner of the function we are executing or to the particular object the function is a method of." http://quirksmode.org/js/this.html

Here is one of simplest programs but it demonstrates the 'this' in two different uses:
var MyFunction = function () {
        console.log(this);
       
    }

MyFunction();
var obj = new MyFunction();

From each of the invocations, the two console outputs look like this:




Now, we have added a local function tryme() to MyFunction(). Again, it starts out by executing line 35 without a variable defining it.

















Since tryme() gets invoked without a variable assigned to it, we get the global this object. Likewise, when MyFunction() is invoked without a variable assigned to it, we get the global object.


Then, with a var obj getting  new MyFunction(), we have MyFunction owner of this, but inside tryme we get default value of this (i.e. window)


Now on to prototypes , its is an object in which other objects inherits properties.
Note that every object has a __proto__ in the debugger. Here is what it provides:









The prototype says if i do not have the property or method that is being requested, go to the 'object' that this field references and look for it.





















After highlighted line executes displaying f



Here we refdefine the class and instead have a prototype method for setName:
var MyFunction = function () {
this.first = 'chris';
this.last = 'cross';
    }

var f = new MyFunction();
MyFunction.prototype.setName = function (_first, _last) {
 this.first = _first;
 this.last = _last;
};

f.setName('cross', 'court');
console.log(f.first);
console.log(f.last);




First: (FROM http://jsfiddle.net/vzFT2/2/):







This value at line 54 before executing the call (global object of window):



Then we step into call at line 54:










the output of line 58 with the hello for property2 (the local_fn.call() populated this as the passed in method):



throw is executed on line 49 which is caught on line 57, line 63 is next function called and this from line 61 has global object:


http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx

http://tech.pro/tutorial/2010/functional-javascript-part-3-apply-call-and-the-arguments-object

 Object.getOwnPropertyNames(Function.prototype);


var MyFunction = function (name, color ){
   var b =  {
  this:this, 
  name:name, 
  color:color
}
console.log(b);
    }
    MyFunction('ipod');
    MyFunction('ipod', 'black');



"call method: method of a function invokes the function with the context variable this set to the first argument passed in, and then each additional argument is passed into the function"

MyFunction('ipod', 'black');
MyFunction.call(window, 'ipod', 'black');

"apply method:invokes the function with the context variable this set to the first argument passed in. The second and final argument, however, will end up being the arguments of the function provided as an array"

ttp://www.smashingmagazine.com/2014/01/23/understanding-javascript-function-prototype-bind/


http://stackoverflow.com/questions/17017115/javascript-call-function

Friday, May 30, 2014

Formatted String to JS Date


From this snippet, decided to use the same inspiration to demo my date conversion function I wrote. It converts dd-MMM-yyyy String to a javascript date:


<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>

 

   ddMMyyyyToJsDate = function(input){

// with ddMMMyyyy passed of  '30-May-2014'
var parts = input.match(/^(\d\d)-(\w{3})-(\d{4})$/);
                // parts[0] is '30-May-2014' , parts[1] is 30 , parts[2] is 'May' , parts[3] is 2014 ,
if((parts == null) ||(parts.length != 4)){
return "Invalid Date";
}
//  converts 'May' to 4
var MMM = "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(parts[2]) / 3  ;
//  verify year of 2014 is 4 digits
if(parts[3].length != 4){
return "Invalid Date";
}
// verify  day is between 1 and 31
if((parts[1] < 1) || (parts[1] > 31)){
return "Invalid Date";
}  
 
// pass in 2014, 4, 30
return new Date(parts[3], MMM , parts[1]); // months are 0-based
}

x = ddMMyyyyToJsDate ('30-May-2014') ;


elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x;                     // Display x in the element

var x; // Declare x

var ddMMyyyyToJsDate ; // Declare converter

</script>

</body>
</html>

Thursday, May 22, 2014

Triangular Meetup May 2014

I went to the Tri-angular meetup and learned about the mean stack (Mongo-Express-Angular-Node). This was held at Ignite Social Media hosted by Darrough West and Keith Morgan.

There is mean.io and meanjs.org . It was suggested its easy to obtain it and get it built just using the node package manager (npm install).  The io one is better choice  as it has an SLA, but they are both pretty similar. However, it is rapidly changing and it does not have a released version.

Passportjs is baked in.

They host their projects on Heroku with MongoHQ.

Koa was mentioned as the "next" express.

Angular and node each have their own routing, but Angular routing invokes the Node routing.

Angular boiler plate was mentioned.

Suggestions with angular:
Try not overload scope, Template cache helpful

Html5 polyfill, respond.js for dealing with ie8

Do not put JQuery in controllers

Promises built in

Factories for http calls

Providers are fancy plugins

No need for undersore, but people like the map/reduce functions

lo-dash a underscre alternative

meteor use on sockets

mention of mongoose

Related post.

Tuesday, May 20, 2014

Angular 101

I am finally getting around to experimenting with Angular. By now you have probably have seen the 20ish minute talk,   or learn it in one day .  But, the first talk I went to on Angular was with The Google Development group here in Triangle last year.

Here is Kyle's sample which I partially modified:









Sample html:
 <div id="tab1EnhancedAddCmts" ng-app="NowPlaying">
                  <div ng-controller="MyCtrl">
                  <input type="text" ng-model="username">
                 <h1>Hello {{username}}</h1>
                <h2>My Favorite Libraries</h2>
              <ul><li ng-repeat="library in libraries">{{library}}</li></ul>
             <button ng-click="doSomething()">Click Me!</button>
             </div>
 </div>

Sample javascript:
<script language="javascript" src="appcontent/js/libs/angular/1.2.16/angular.min.js"></script>

<script type="text/javascript" language="javascript">
                                   
var app = angular.module('NowPlaying', []);

app.controller(‘MyCtrl’, ['$scope', ' NowPlayingSvc',
       function($scope,    NowPlayingSvc) {
                    
            $scope.doSomething = function() {
                    
            alert('doSomething');

            NowPlayingSvc.libraries.push($scope.username);                                                                                                                      

       };


        $scope.username = 'Kyle Buchanan';

        $scope.libraries = NowPlayingSvc.libraries;
}]);

                       
app.factory('NowPlayingSvc', [
       function() {
            return {
                     libraries: [
                                    'MooTools',
                                     'Scriptaculous'
                                      'Ember'
                                 ]
             };
}]);


</script>




More info: