Mis primeros pasos con JavaScript

Alexandra Vargas

 @axelav

Medellin Js

18 de Diciembre de 2014

Como termine usando JS

Ctrl+C and Ctrl + V

$(function(){
        var carousel = $('.carousel ul');
        var carouselChild = carousel.find('li');
        var clickCount = 0;
        var canClick = true;

        itemWidth = carousel.find('li:first').width()+1; //Including margin

        //Set Carousel width so it won't wrap
        carousel.width(itemWidth*carouselChild.length);

        //Place the child elements to their original locations.
        refreshChildPosition();

        //Set the event handlers for buttons.
        $('.btnNext').click(function(){
            if(canClick){
                canClick = false;
                clickCount++;

                //Animate the slider to left as item width 
                carousel.stop(false, true).animate({
                    left : '-='+itemWidth
                },300, function(){
                    //Find the first item and append it as the last item.
                    lastItem = carousel.find('li:first');
                    lastItem.remove().appendTo(carousel);
                    lastItem.css('left', ((carouselChild.length-1)*(itemWidth))+(clickCount*itemWidth));
                    canClick = true;
                });
            }
        });

        $('.btnPrevious').click(function(){
            if(canClick){
                canClick = false;
                clickCount--;
                //Find the first item and append it as the last item.
                lastItem = carousel.find('li:last');
                lastItem.remove().prependTo(carousel);

                lastItem.css('left', itemWidth*clickCount);             
                //Animate the slider to right as item width 
                carousel.finish(true).animate({
                    left: '+='+itemWidth
                },300, function(){
                    canClick = true;
                });
            }
        });

        function refreshChildPosition(){
            carouselChild.each(function(){
                $(this).css('left', itemWidth*carouselChild.index($(this)));
            });
        }
    });

Ajax...forms

 request = $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData
    });

Angular Js

Aprendi Conceptos Claves

  • Javascript es un lenguaje que se define como orientado a Objetos
  • Objetos
  • This
  • Scope

Objetos

Contenedor de propiedades , una propiedad tiene un nombre y un valor, el valor puede ser cualquiera.

 

Tipos Primitivos:

Numbers, string, boolean

 

Objetos: 

Functions, arrays, regular expressions, null  y objects 

 

//Notacion Literal


var persona = {
  'nombre':'Clark Ken',
  'apellido': ''
};

var superHeroe = {
  alias: function (){
      return 'superman';
  }
};

console.log(persona.nombre);
console.log(superHeroe.alias());

This

Variable que se define automáticamente cuando una función es invocada

 

El valor que retorna depende de donde se invoca la función.

 

Contexto Global

Contexto Función

Contexto Objeto

 

var miObjeto = {
    get: function miMetodo() {
        return this.val;
    },
    val : 42
};

console.log(miObjeto.get());


//Entendiendo This

function miMetodo(){
  return this.val;
}

var miObjeto1 = {
  get: miMetodo,
  val: 222
};


var miObjeto2 = {
  get: miMetodo,
  val: 999
};

console.log(miObjeto1.get());

console.log(miObjeto2.get());

Scope

Es la visibilidad de las variables

 

En Js el scope de las variables es por funciones.

var globalVariable = 'mi variable global';

function ejemploScope(){
  var globalVariable = 'mi variable local o.O';
}

console.log(globalVariable);

ejemploScope();

console.log(globalVariable);

//Lifetime Variables

function local(){
    var localVariable = 'mi variable local2 o.O ';
    localVariable3 = 'mi variable local3 o.O ';
}

local();
console.log(localVariable);
console.log(localVariable3);

Pero.....

Backbone

 

Aprendi mas... y mas...

  • Javascript no solo manipula el DOM
  • Prototype
  • Functions
  • Callbacks
  • Promises
  • Hoisting

Prototype

 

Cada objeto en Js tiene enlazado un prototype.

 

Javascript tiene herencia prototipada.

//Modelo Clasico

function Mother(){}

Mother.prototype.getName = function(){
  return this.name;
};

var lucy = new Mother();
lucy.name = 'Lucy';

//console.log(lucy.getName());

function Son() {}
Son.prototype = new Mother();


var carlos = new Son();
carlos.name = 'carlos';

//console.log(carlos.getName());
//console.log(carlos instanceof Mother);
//console.log(carlos instanceof Son);

Functions

Son bloques de código que encierran instrucciones.

 

Js también implementa conceptos de lenguaje funcional.

 

Las funciones pueden:

* Asignarse a variables

* Pasarse como parametros

* Retornarse

 

 

 

 

 

 

//Funciones Literales

var funcion1 = function (){
  return 'Hola soy una funcion';
};

//Metodo

var objeto1 = {
  'metodo': function (){
    return 'Soy la funcion 2';
  }
};

//Como argumento

function sumar (numeros,regalos){
  return numeros()+regalos;
}

var numeros = function(){
  return 1+2+3;
};

sumar(numeros,1);

Closures

Función declarada dentro de otra función que usa el entorno en el que fue declarada.

function init() {
    var name = "Medellin Js"; // name is a local variable created by init
    function displayName() { // displayName() is the inner function, a closure
        alert (name); // displayName() uses variable declared in the parent function    
    }
    displayName();    
}
init();

Callbacks

Funciones que se ejecutan una vez pasa algo, se usan normalmente para peticiones asincronas

Promises

Objeto que permite ejecutar operaciones asíncronas en base a un estado.

 

Estados:

  • Completas
  • Fallidas
  • Espera

Hoisting

Es la manera en que Javascript mueve las funciones y variables al comienzo.

var myVar = 'Mi variable global';

function changing (){
  console.log(myVar);
  var myVar = 'Mi variable local';
  console.log(myVar);
}

changing();

Lo que me gusta

 

  • Ampliamente soportado, en el cliente, servidor
  • El entorno para comenzar a desarrollar es mínimo
  • Comunidad
  • La documentacion
  • Debilmente tipado

Lo que no me gusta

  • Variables globales
  • Scope confuso
  • Contextos  (this)
  • Debilmente tipado

Ahora se.... que nada se

Inspiracion

Most programming languages contain good parts and bad parts. I discovered that I could be a better programmer by using only the good parts and avoiding the bad parts

Mis primeros pasos con Javascript

By Maria Alexandra Vargas Ortega

Mis primeros pasos con Javascript

  • 2,254