Difference between revisions of "Javascript"
(→Named Arguments) |
(→Test) |
||
(6 intermediate revisions by the same user not shown) | |||
Line 99: | Line 99: | ||
car.prototype.brake = function { alert('Brake');}; | car.prototype.brake = function { alert('Brake');}; | ||
</source> | </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 == | ||
Line 184: | 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
Contents
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;
}