Difference between revisions of "Javascript"

From no name for this wiki
Jump to: navigation, search
(Array Objekt)
(Test)
(18 intermediate revisions by the same user not shown)
Line 10: Line 10:
  
  
Anderes Array Sample:
+
  //Anderes Array Sample:
 
  var myArray = [8,7,6,5];
 
  var myArray = [8,7,6,5];
 
  alert(myArray[0]); //Druckt 8
 
  alert(myArray[0]); //Druckt 8
Line 23: Line 23:
 
== Properties ==
 
== Properties ==
 
Properties mit [] setzen:
 
Properties mit [] setzen:
 +
 +
<source lang="javascript">
 
  var myObject = new Object();
 
  var myObject = new Object();
 
  myObject["myProperty"] = 5;
 
  myObject["myProperty"] = 5;
 
  alert(myObject.myProperty); //Sollte 5 anzeigen
 
  alert(myObject.myProperty); //Sollte 5 anzeigen
 +
</source>
  
 
== Closures ==
 
== Closures ==
 
Hello World, inline:
 
Hello World, inline:
 +
<source lang="javascript">
 
  var myClosure = function(){alert ('Hello World');};
 
  var myClosure = function(){alert ('Hello World');};
 
  myClosure();
 
  myClosure();
 +
</source>
  
 
Hello World:
 
Hello World:
 +
<source lang="javascript">
 
  function helloWorld(){alert ('Hello World');}
 
  function helloWorld(){alert ('Hello World');}
 
  var myClosure = helloWorld;
 
  var myClosure = helloWorld;
 
  myClosure();
 
  myClosure();
+
</source>
  
 
== Klassen ==
 
== Klassen ==
 
In Javascript kann man Klassen wie folgt erstellen:
 
In Javascript kann man Klassen wie folgt erstellen:
 +
<source lang="javascript">
 
  function Car(size, color, numdoors){
 
  function Car(size, color, numdoors){
 
   this.size = size;
 
   this.size = size;
Line 45: Line 52:
 
   this.numdoors = numdoors;  
 
   this.numdoors = numdoors;  
 
  }
 
  }
 +
</source>
 
   
 
   
 
So werden Instanzen erstellt:
 
So werden Instanzen erstellt:
 +
<source lang="javascript">
 
  var myCar = new Car(23,"Green",5);
 
  var myCar = new Car(23,"Green",5);
 
  var numDoorsOfmyCar = myCar.numdoors;
 
  var numDoorsOfmyCar = myCar.numdoors;
 +
</source>
  
 
Member Funktionen
 
Member Funktionen
 +
<source lang="javascript">
 
  function Car(numdoors){   
 
  function Car(numdoors){   
 
   this.numdoors = numdoors;  
 
   this.numdoors = numdoors;  
Line 59: Line 70:
 
   alert('brake');
 
   alert('brake');
 
  }
 
  }
 +
</source>
  
 
=== Grundfunktionen ===
 
=== Grundfunktionen ===
Line 66: Line 78:
  
 
Funktion mit Objekt als Argument:
 
Funktion mit Objekt als Argument:
 
+
<source lang="javascript">
 
  //square ist ein Objekt mit den erwarteten Properties height und width
 
  //square ist ein Objekt mit den erwarteten Properties height und width
 
  function area(square) {
 
  function area(square) {
Line 72: Line 84:
 
  }
 
  }
  
Hier der Funktionsaufruf mit named Arguments:
+
//Hier der Funktionsaufruf mit named Arguments:
 
  var myresult =  area({height: 30, width : 30});
 
  var myresult =  area({height: 30, width : 30});
 
  alert(myresult);
 
  alert(myresult);
 +
</source>
  
 
== Prototype ==
 
== Prototype ==
 
Mit dem Keyword Prototype kann ein neues Property für alle Instanzen einer Klasse erstellt werden:
 
Mit dem Keyword Prototype kann ein neues Property für alle Instanzen einer Klasse erstellt werden:
 
+
<source lang="javascript">
 
  //Definition der Klasse Car
 
  //Definition der Klasse Car
 
  function car(){}
 
  function car(){}
Line 85: Line 98:
 
  //Nun eine Funktion definieren
 
  //Nun eine Funktion definieren
 
  car.prototype.brake = function { alert('Brake');};
 
  car.prototype.brake = function { alert('Brake');};
 +
</source>
 +
 +
== watch ==
 +
<source lang="javascript">
 +
var o = { p: 1 };
 +
 +
o.watch("p", function (id, oldval, newval) {
 +
    console.log( "o." + id + " changed from " + oldval + " to " + newval );
 +
    return newval;
 +
});
 +
 +
o.p = 2;
 +
o.p = 3;
 +
delete o.p;
 +
o.p = 4;
 +
 +
o.unwatch('p');
 +
o.p = 5;
 +
</source>
 +
 +
Output:
 +
o.p changed from 1 to 2
 +
o.p changed from 2 to 3
 +
o.p changed from undefined to 4
  
 
== Funktionsargumente ==
 
== Funktionsargumente ==
 
Die implizite Variable arguments:
 
Die implizite Variable arguments:
 +
 +
<source lang="javascript">
 
  function sum() {
 
  function sum() {
 
   var myresult = 0;
 
   var myresult = 0;
Line 97: Line 136:
 
   
 
   
 
  var myresult =  sum(23,23,23);
 
  var myresult =  sum(23,23,23);
 
+
</source>
 
<tt>arguments</tt> bietet noch mehr: <tt>arguments.callee</tt>, <tt>arguments.caller</tt> und weiteres.
 
<tt>arguments</tt> bietet noch mehr: <tt>arguments.callee</tt>, <tt>arguments.caller</tt> und weiteres.
  
 
== Exceptions ==
 
== Exceptions ==
 +
<source lang="javascript">
 
  try {  
 
  try {  
 
    
 
    
Line 109: Line 149:
 
     alert(er);   
 
     alert(er);   
 
  }
 
  }
 +
</source>
  
 
== with ==
 
== with ==
 
Mit with kann man ein Objekt zum default Objekt machen:
 
Mit with kann man ein Objekt zum default Objekt machen:
 +
<source lang="javascript">
 
  var myObject = new Obect();
 
  var myObject = new Obect();
 
  myObject.myproperty = 3;
 
  myObject.myproperty = 3;
Line 117: Line 159:
 
     alert(myproperty); //Shows 3
 
     alert(myproperty); //Shows 3
 
  }
 
  }
 +
</source>
  
 
== HTML Countdown ==
 
== HTML Countdown ==
Line 164: Line 207:
 
// -->
 
// -->
 
</script>
 
</script>
 +
</source>
 +
 +
== Function in Function ==
 +
The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function. n this example, the baz function will be available for use after the foo function has been run, as it's overridden window.baz. The bar function will not be available to any context other than scopes contained within the foo function.
 +
 +
<source lang="javascript">
 +
function foo(doBar)
 +
{
 +
  function bar()
 +
  {
 +
    console.log( 'bar' );
 +
  }
 +
 +
  function baz()
 +
  {
 +
    console.log( 'baz' );
 +
  }
 +
 +
  window.baz = baz;
 +
  if ( doBar ) bar();
 +
}
 +
</source>
 +
 +
== Undefined ==
 +
<source lang="javascript">
 +
if( typeof foo != 'undefined' ) {
 +
alert('defined');
 +
}
 +
else
 +
{
 +
alert('undefined');
 +
}
 
</source>
 
</source>
  
 
== Links ==
 
== Links ==
 
* [[AJAX]]
 
* [[AJAX]]
 +
 +
== JQuery ==
 +
=== Dropdowninhalt anhand anderem Dropdown auffüllen ===
 +
<source lang="javascript">
 +
  $(function () {
 +
 +
                  $("#ddlVerfuegbarePlaetze").change(function () {
 +
 +
                      var option = $(this).val();
 +
 +
                      $.ajax({
 +
                          type: "POST",
 +
                          url: "Reservierung.aspx/GetAnzahlFreiePlaetze",
 +
                          contentType: "application/json; charset=utf-8",
 +
 +
                          data: "{'fuehrungId':'" + option + "'}",
 +
 +
                          success: function (msg) {
 +
                              fillDropDown(msg.d);
 +
                          },
 +
                          error: function (res, status) {
 +
                              if (status === "error") {
 +
                                  // errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
 +
                                  var errorMessage = $.parseJSON(res.responseText);
 +
                                  alert(errorMessage.Message);
 +
                              }
 +
                          }
 +
                      });
 +
 +
 +
 +
 +
 +
 +
                  });
 +
 +
              });
 +
             
 +
              function fillDropDown(freiePlatze) {
 +
                  $("select#ddlAnzahlTeilnehmer").empty();
 +
                  $("select#ddlAnzahlTeilnehmer").append(
 +
                          $("<option>").val("").html("")
 +
                  );
 +
                  for (var i = 1; i < freiePlatze; i++) {
 +
                      $("select#ddlAnzahlTeilnehmer").append(
 +
                          $("<option>").val(i.toString()).html(i.toString())
 +
                      );
 +
                  }
 +
              }
 +
</source>
 +
 +
Aspx, code behind:
 +
 +
<source lang="csharp">
 +
      [WebMethod]
 +
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
 +
        public static int GetAnzahlFreiePlaetze(int fuehrungId)
 +
        {
 +
            if (IsUserInRole(GlobalConstants.RoleAdmin))
 +
            {
 +
                return
 +
                    AppGlobal.Repository<IConfigurationEntryRepository>()
 +
                            .GetValue<int>(GlobalConstants.ConfigMaxTeilnehmerAdmin);
 +
            }
 +
 +
            int res = AppGlobal.Repository<IAnzahlTeilnehmerRepository>().GetAnzahlFreiePlaetze(fuehrungId);
 +
            int max =
 +
                AppGlobal.Repository<IConfigurationEntryRepository>()
 +
                        .GetValue<int>(GlobalConstants.ConfigMaxTeilnehmerUser) + 1;
 +
 +
            if (res <= max)
 +
            {
 +
                return res;
 +
            }
 +
            return max;           
 +
        }
 +
</source>

Revision as of 09:48, 30 November 2014

Hier ein paar Samples

Array Objekt

Objekt Array erstellen:

 var myArray = new Array("elem1", "elem2", "elem3");
 var poppedElem = myArray.pop(); //Stack Pop Operation
 myArray.concat(new Array("elem3","elem4")); //Zusammenfügen von Arrays


  //Anderes Array Sample:
 var myArray = [8,7,6,5];
 alert(myArray[0]); //Druckt 8
 for(var i=0; i<myArray.lenght; i++){
   alert(myArray[i]);
 }

Weitere Funktionen

Array bietet noch (nicht abschliessend): sort, reverse, splice, join und viele mehr.

Properties

Properties mit [] setzen:

 var myObject = new Object();
 myObject["myProperty"] = 5;
 alert(myObject.myProperty); //Sollte 5 anzeigen

Closures

Hello World, inline:

 var myClosure = function(){alert ('Hello World');};
 myClosure();

Hello World:

 function helloWorld(){alert ('Hello World');}
 var myClosure = helloWorld;
 myClosure();

Klassen

In Javascript kann man Klassen wie folgt erstellen:

 function Car(size, color, numdoors){
   this.size = size;
   this.color = color;
   this.numdoors = numdoors; 
 }

So werden Instanzen erstellt:

 var myCar = new Car(23,"Green",5);
 var numDoorsOfmyCar = myCar.numdoors;

Member Funktionen

 function Car(numdoors){   
   this.numdoors = numdoors; 
   this.brake = brake;
 }

 function brake(){
   alert('brake');
 }

Grundfunktionen

Es gibt eine Properties, welche alle Objekte haben. Nicht abschliessend: toString, watch und unwatch, constructor, prototype, hasOwnProperty, prototype.isPrototypeOf, propertyIsEnumerable, toSource, valueOf, eval

Named Arguments

Funktion mit Objekt als Argument:

 //square ist ein Objekt mit den erwarteten Properties height und width
 function area(square) {
    return square.height * square.width;  
 }

//Hier der Funktionsaufruf mit named Arguments:
 var myresult =  area({height: 30, width : 30});
 alert(myresult);

Prototype

Mit dem Keyword Prototype kann ein neues Property für alle Instanzen einer Klasse erstellt werden:

 //Definition der Klasse Car
 function car(){}
 //Nun ein Property definieren
 car.prototype.numwheels = 4;
 //Nun eine Funktion definieren
 car.prototype.brake = function { alert('Brake');};

watch

var o = { p: 1 };

o.watch("p", function (id, oldval, newval) {
    console.log( "o." + id + " changed from " + oldval + " to " + newval );
    return newval;
});

o.p = 2;
o.p = 3;
delete o.p;
o.p = 4;

o.unwatch('p');
o.p = 5;

Output: o.p changed from 1 to 2 o.p changed from 2 to 3 o.p changed from undefined to 4

Funktionsargumente

Die implizite Variable arguments:

 function sum() {
   var myresult = 0;
   for(int i=0; i<arguments.length; i++){
      myResult += arguments[i];
   }
   return myresult;
 }
 
 var myresult =  sum(23,23,23);

arguments bietet noch mehr: arguments.callee, arguments.caller und weiteres.

Exceptions

 try { 
   
      throw "An error" 
 } 
 catch(er) {
    //er is a string  
    alert(er);  
 }

with

Mit with kann man ein Objekt zum default Objekt machen:

 var myObject = new Obect();
 myObject.myproperty = 3;
 with(myObject){
    alert(myproperty); //Shows 3
 }

HTML Countdown

var countdowndata;

function countdown() {
                
   countdowndata = new Object();   
   countdowndata.time = new Date();  
   countdowndata.time.setTime(countdowndata.time.getTime() + (1000*60*3))
   
   setTimeout('countdonwcallback()',200);      
}

function countdonwcallback() {
   var divcountdown = document.getElementById('countdown'); 
   var nowDate = new Date();
   
   var timeDiff = countdowndata.time.getTime() - nowDate.getTime();
   
   var mins = Math.floor((timeDiff)/(1000*60));
   var secs = Math.floor((timeDiff)/1000) % 60;
   
   if(secs < 10)
   {
      divcountdown.innerHTML  = "" + mins + ":0" + secs; 
   }
   else 
   {
      divcountdown.innerHTML  = "" + mins + ":" + secs; 
   }
   setTimeout('countdonwcallback()',200);
}

Popup

<script language="javascript" type="text/javascript">
<!--
function popitup(url) {
	newwindow=window.open(url,'name','height=200,width=150');
	if (window.focus) {newwindow.focus()}
	return false;
}

// -->
</script>

Function in Function

The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function. n this example, the baz function will be available for use after the foo function has been run, as it's overridden window.baz. The bar function will not be available to any context other than scopes contained within the foo function.

function foo(doBar)
{
  function bar()
  {
    console.log( 'bar' );
  }

  function baz()
  {
    console.log( 'baz' );
  }

  window.baz = baz;
  if ( doBar ) bar();
}

Undefined

if( typeof foo != 'undefined' ) { 
	alert('defined');
}
else
{
	alert('undefined');
}

Links

JQuery

Dropdowninhalt anhand anderem Dropdown auffüllen

   $(function () {

                   $("#ddlVerfuegbarePlaetze").change(function () {

                       var option = $(this).val();

                       $.ajax({
                           type: "POST",
                           url: "Reservierung.aspx/GetAnzahlFreiePlaetze",
                           contentType: "application/json; charset=utf-8",

                           data: "{'fuehrungId':'" + option + "'}",

                           success: function (msg) {
                               fillDropDown(msg.d);
                           },
                           error: function (res, status) {
                               if (status === "error") {
                                   // errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
                                   var errorMessage = $.parseJSON(res.responseText);
                                   alert(errorMessage.Message);
                               }
                           }
                       });






                   });

               });
               
               function fillDropDown(freiePlatze) {
                   $("select#ddlAnzahlTeilnehmer").empty();
                   $("select#ddlAnzahlTeilnehmer").append(
                           $("<option>").val("").html("")
                   );
                   for (var i = 1; i < freiePlatze; i++) {
                       $("select#ddlAnzahlTeilnehmer").append(
                           $("<option>").val(i.toString()).html(i.toString())
                       );
                   }
               }

Aspx, code behind:

      [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static int GetAnzahlFreiePlaetze(int fuehrungId)
        {
            if (IsUserInRole(GlobalConstants.RoleAdmin))
            {
                return
                    AppGlobal.Repository<IConfigurationEntryRepository>()
                             .GetValue<int>(GlobalConstants.ConfigMaxTeilnehmerAdmin);
            }

            int res = AppGlobal.Repository<IAnzahlTeilnehmerRepository>().GetAnzahlFreiePlaetze(fuehrungId);
            int max =
                AppGlobal.Repository<IConfigurationEntryRepository>()
                         .GetValue<int>(GlobalConstants.ConfigMaxTeilnehmerUser) + 1;

            if (res <= max)
            {
                return res;
            }
            return max;            
        }