Document Details

EffusiveQuail2237

Uploaded by EffusiveQuail2237

Virtual University of Pakistan

Tags

WPF programming commands application commands computer science

Summary

These are short notes on chapter 24 of CS411, focusing on WPF commands and their implementation in applications. The document provides details about built-in commands and custom commands.

Full Transcript

www.vuanswer.com CS411 Short Notes Chapter No 24 Short Notes 1). Commands are a more robust and loosely coupled version of:  Events 2). WPF defines a number of  Built-in Commands 3). Any object can work as a command by:  Impleme...

www.vuanswer.com CS411 Short Notes Chapter No 24 Short Notes 1). Commands are a more robust and loosely coupled version of:  Events 2). WPF defines a number of  Built-in Commands 3). Any object can work as a command by:  Implementing icommand 4). icommand includes:  Execute  CanExecute  CanExecuteChanged 5). For cut, copy and paste we can define and implement three classes mplementing  icommand 6).Pre-defined Built-in Commands:  Application Commands  Component Commands  Media Commands  Navigation commands  Editing Commands 7). All instances of RoutedUiCommand implement icommand and support bubbling 8). Custom Commands don’t get the treatment of CommandConverter. 9). You can add KeyBinding and MouseBinding yourself. 10). Example of KeyBinding: www.vuanswer.com www.vuanswer.com  This.InputBinding.Add(New KeyBinding(ApplicationCommands.Help, new KesyGeasture(Key.F2)));   This.InputBinding.Ass(New KeyBinding(ApplicationCommands.NotaCommand, new KeyGesture(Key.F1))); 11) TextBox is an example of Control with builtin command binding that responds to ctrl-z etc. 12) WPF Input Events make possible rich interactive content. 13) Application Commands: Close Save Copy SaveAll New Stop Open Undo Cut Delete Print Find Properties Replace Save SaveAs Stop Undo 14) Component Commands: MoveDown ScrollPageRight MoveLeft ScrollPageUp MoveRight SelectToHome SelectToEnd MoveUp ScrollByLine SelectToPageDown ScrollPageDown SelectToPageUp ScrollPageLeft 15) Media Commands: ChannelDown ChannelUp DecreaseVolume FastForward IncreaseVolume MuteVolume NextTrack Pause Play PreviousTrack Record Rewind www.vuanswer.com www.vuanswer.com Select Stop 16) Navigation Commands: BrowseBack BrowseForward BrowseHome BrowseStop Favorites FirstPage GoToPage LastPage NextPage PreviousPage Refresh Search Zoom 17) Editing Commands: AlignCenter AlignJustify AlignLeft AlignRight CorrectSpellingError DecreaseFontSize DecreaseIndentation EnterLineBreak EnterParagraphBreak IgnoreSpellingError IncreaseFontSize IncreaseIndentation MoveDownByLine MoveDownByPage MoveDownByParagraph MoveLeftByCharacter MoveLeftByWord MoveRightByCharacter MoveRightByWord www.vuanswer.com www.vuanswer.com Chapter NO.25 Short Notes 1).WPF Window is a:  win32 window 2). Any Number of child windows can be made by  instantiating a window derived class and calling show 3). Child windows gets closed or minimized:  on closing or minimizing of parent window 4). Window Events include:  Activated  Deactivated 5).Using Window.Show() a window appears and then disappears 6). StartupUri in xaml is 7). main() is created dynamically 8). System.Environment.GetCommandLineArgs is used to get command line arguments in WPF 9). Application Level Events are:  Startup  Exit  Activated  Deactivated  SessionEnding www.vuanswer.com www.vuanswer.com 10). Window.show() is used to instantiate (Read-only) window. 11). Properties Dictionary is a simple Dictionary used to share things among different windows. 12). Application.Current() is used to take current window from any app. 13). Dispatcher.Run() is used to make multiple UI threads. 14). Single Instance App: Bool mutexIsNew; using (System.Threading.Mutex m = New System.Threading.Mutex(True, uniqueName, out mutexIsNew)) { if(mutexIsNew) // This is the first instance. Run the application else // There is already an instance running } 15). Dialogs are just child windows 16).There are two types of dialogs:  Modal  Modeless  17). Modeless Dialog are more like normal Windows. 18). Modal Dialog are such windows that are necessary to terminate explicitly in order to interact with main window. 19). In modeless Window we can work in parallel with main window just like using Tools window in Photoshop. 20).Common Dialogs are actually provided by win32 and are part of Modal dialog. 21). Custom Dialogs are user-defined. 22). ShowDialog() returns us Null-able Boolean with options True/False/Null. 23). Apllication Deploy include:  ClickOnce www.vuanswer.com www.vuanswer.com  Windows Installer 24). EULA stand for End User License. 25). Benefits of Windows Installer:  showing custom setup UI like EULA  Control over where files are installed  Arbitrary code at install time  Register COM components and File Association  Install for All users  Installation From CD 26). Benefits of ClickOnce:  Built-in support for automatic updates and roll back to previous version  A web-like go-away experience  Start-menu or control panel program list  All files in isolated area  Clean Un-installation www.vuanswer.com www.vuanswer.com Chapter NO.26 Short Notes 1) Wizard is a Dialog Box with multiple User-Interfaces. 2). Difference Between Page and Window: Page in itself cannot Display. Window is an area containing page. 3). Child windows gets closed or minimized:  on closing or minimizing of parent window 4). Navigation Based apps are:  Windows Explorer  Media Player  Photo Gallery 5). Host Windows are:  Navigation Window  Frame 6). Navigation Containers Provide:  Navigating  History Journal  Navigation Related events 7). Difference between Navigation Window and Frame: Navigation window gives you a navigation Bar by default while Frame does not. Navigation Window is more like a top-level window wherease Frame more like an HTML frame or iFrame. 8). Page does everything that windows does except OnClosed and OnClosing. 9). Navigation can also happen between HTML files. 10). A page can interact with its Navigation Container by using NavigationService Class. www.vuanswer.com www.vuanswer.com 11). You can get an instance of NavigationService by calling the static NavigationService.GetNavigationService method and passing an instance of the page. 12). this.NavigationService.Refresh() results in reload of current page. 13). Performing navigation in 3 main ways:  calling navigation method  Using Hyperlinks  Using the Journal 14). Properties of page:  WindowHeight  WindowWidth  WindowTitle 15). Example Of Navigate Method: PhotoPage nextPage = new PhotoPage(); this.NavigationService.Navigate(nextPage); 16). Navigate to a page via Uri this.NavigateService.Navigate(new Uri(“photoPage.xaml”, uriKind.Relative)); 17). Example of navigation using Hyperlink. Click Here to view the photo 18). Journal provides logic behind back and frwd. 19). Two internal stacks are:  Undo  Redo www.vuanswer.com www.vuanswer.com 20).Navigation Window always has a journal but frame may depending on its JournalOwnership = OwnsJournal, UseParenJournal, Automatic 21). When frame has journal it has back/frwd buttons but can set NavigationUiVisibility = Hidden 22). Navigation Events that raise when loading first page: See in handouts 23). Navigation Events that raise when navigating between pages. See handouts 23). NavigationIsstopped is an event called instead of LoadCompleted if an error occurs or navigation is cancelled. 24). Html to html event firing is not allowed. 25). PageFunction has special mechanism for returning data. www.vuanswer.com www.vuanswer.com Chapter NO.27 Short Notes 1). Browser based Applications are partial trust applications. 2). Partial Trust means with some restrictions. 3). Basic benefit of Silverlight is that it is cross-platform. But WPF browser based applications just run on windows. 4). In Web Based applications the journal of Application and Web Browser are integrated. 5). GAC is a Global Assembly Cache 6). ClickOnce Applications are chached. 7). How to open file from local system: String filecontents = null; OpenFileDialog ofd = new openFileDialog(); if(ofd.ShowDialog()==true) { using(stream s = ofd.OpenFile()) using(StreamReader sr = new StreamReader()) { filecontent = sr.ReadToEnd(); } } 8). Data can be given to any web site using two method:  URL Parameter  Cookies 9). BrowserInteropHelper.Source to retrieve the complete URL. 10). Browse Cookies retrieved by Application.GetCookie method. www.vuanswer.com www.vuanswer.com 11). Two steps of making full-trusted Web Browser App.  Change: Internet to Custom  Add: 12). To publish a web based application use VS publishing wizard or mage tool in SDK and copy files to webserver which must be configured to serve it. 13). Users can install and run a web based application just by navigating to a URL. 14). Resources can be:  Binary  Logical 15)..Net has binary resources in WPF. 16). Binary resources can be:  Embedded(part of exe)  Stored at Known place 17). Localization: Localization means that your application can target more than one target languages or target Grammers. 18). In Order to localize resources its necessary to make them embedded resources. www.vuanswer.com www.vuanswer.com Chapter NO.28 Short Notes 1) How to specify Default Culture of Application: en-US [assembly: NautralResourceLanguage(“en-US”, UltimateResourceFallBackLocation.Satellite] 2). Logical Resources are arbitrary.net objects stored and named in an element Resource Properties. 3). By using logical resources we can save change in one place and have different effects. Like you can change brushes in one place and have different effects. 4). Logical Resources can further be categorized in “Static Resources” and “Dynamic Resources”. 5). In Dynamic Resources we actually subscribe to the updates of the resource. 6). In static resource we just want its value once. 7). Static Resource markup extension walks the logical tree or even application level or system Resources. 8). Example of Static Resource: www.vuanswer.com www.vuanswer.com 9). Static Resources do not support forward references. 10). Static Resources do not support Sharing. 11). Procedural Code/Static Resource: window.Resources.add(“BackgroundBrush”, new SolidColorBrush(Colors.Yellow)); Window.Resources.Add(“BorderBrush”, new SolidColorBrush(Colors.Red)); Button button = new Button(); StackPanel.Children.Add(button); Button.Background = (Brush)button.FindResource(“BackgroundBrush”); Button.BorderBrush = (Brush)button.FindResource(“BorderBrush); 12). Procedural Code/Dynamic Resource Button button = new Button(); Button.SetResourceReference(Button.BackgroundProperty, “BackgroundBrush”); Button.SetResourceReference(Button.BorderBrushProperty, “BorderBrush”); Button button = new Button(); Button.Background = (Brush)window.Resources[“BackgroundBrush”]; Button.BorderBrush = (Brush)window.Resources[“BorderBrush ”]; 13). The key benefit of logical resources is that Use and definition becomes seprate. 14). System Resources are such resources which are shared by al application For Example: System Color, System font, System Parameters. www.vuanswer.com www.vuanswer.com Chapter NO.29 Short Notes 1). Data Binding allows to declaratively bind two different properties in xaml. 2). Binding Object has one source and target Object. 3). Binding binds two propertiews together and keeps a communication channel open. 4). Example code of binding: public mainWindow() { InitializeComponent(); Binding binding = new Binding(); Binding.Source = TreeView; Binding.Path = new PropertyPath(“SelectedItem.Header”); CurrentFolder.SetBinding(TextBlock.TextProperty, binding); } 5). Property.Pah can also use  BindingOperation.SetBinding  BindingOperation.ClearBinding  BindingOperation.ClearAllBindings 6). The DisplayMemberPath property can be used to improve display: 7). Synchronization means binding multiple targets with single source. 8). Example Code Of Synchronization: { Thread.Sleep(2000); Console.WriteLine(“Foo”); }); Console.WriteLine(task.IsCompleted); task.Wait(); 15). Example of exception handling with tasks: Task task = Task.Run(()=>{throw null;}); Try { Task.Wait(); } catch(AggregateException aex) { if(aex.InnerException is NullReferenceException) Console.WriteLine(“Null”); else www.vuanswer.com www.vuanswer.com throw; } 16). Create a task which you can wait and attach continuations. Controlled by the following operations: public class TaskCompletionSource { public void SetResult(TResult result); public void SetException(Exception exception); public void SetCanceled(); public bool TrysetResult(TResult result); public bool TrySetException(Exception exception); public bool TrySetCanceled(); } 17). What would be the result of following piece of code: Var tcs = new TaskCompletionSource(); new Thread(()=>{Thread.Sleep(5000); tcs.SetResult(42); }).Start(); Task task = tcs.Task; Console.WriteLine(task.Result); This code will print 42 after 5s. 18). How to use Delay method:  Task.Delay(5000).GetAwaiter().OnCompleted(()=>Console.WriteLine(42));  Task.Delay(5000).ContinueWith(ant=>Console.WriteLine(42)); www.vuanswer.com www.vuanswer.com Chapter NO.34 Short Notes 1). Asynchronous takes return quickly. 2). Asynchronous are non-blocking. 3). For I/O bound we can usually work without thread. 4). For CPU bound we can start and return task and are asynchronous tasks. 5). Example of CPU bound asyn Task: Int GetPrimesCount(int start, int count) { ParallelEnumerable.Range(start, count).count(n=>Enumerable.Range(2,(int)Math.Sqrt(n)- 1).All(i=>n%i>0)); } void DisplayPrimeCounts() { for(int i = 0; i DisplayPrimeCounts()); Task GetPrimesCountAsyn(int start, int count) { Return Task.Run(()=> ParallelEnumerable.Range(start, count).Count(n=>Enumerable.Range(2, (int)Math.Sqrt(n)-1).All(i=>n%i>0))); } for(int i = 0; i Console.WriteLine(awaiter.GetResult()+” primes between….”)); www.vuanswer.com www.vuanswer.com } Console.WriteLine(“Done”); 7). The above code is simple in C#5.0: Asyn Task DisplayPrimeCounts() { for(int i = 0; ifire an event handler user BeginInvoke/Invoke message-> execute delegate } www.vuanswer.com www.vuanswer.com Chapter NO.35 Short Notes 1). Write Downloading Code: asyn void Go() _button.IsEnabled = false; String[] urls = www.albahri.com www.orielly.com www.linqpad.net.Split(); Int totallength = 0; try{ foreach(String url in urls) { var uri = new Uri(“http://”+url); Byte[] data = await new WebClient().DownloadDataTaskAsync(url); _results.Text+ “Length of “+url+ “ is “+data.Length+Environmentr.newLine; TotalLength+=data.Length; } _result.Text+=”Total length : “+TotalLength; } catch(WebException ex) { _result.Text+=”error: “+ex.Message; } finally{_button.IsEnabled = true;} } 2). We can return a Task from void function without explicitly returning it. 3). If you have to write asynchronous function then follow three steps:  Write its totally synchronous version  Then use await and async  Then use returnand return Task in place of void 4). Example of async chaining: async Task Go() { var task = PrintAnswerToLife(); www.vuanswer.com www.vuanswer.com await task; Console.WriteLine(“Done”); } async Task GetAnswerToLife() { var task = Task.Delay(5000); await task; int answer = 21*2; return answer; } 5). Example of Parallelism: var task1 = PrintAnswerToLife(); var task2 = PrintAnswerToLife(); await task1; await task2; async Task GetAnswerToLife() { _x++; await Task.Delay(5000); return 21*2; } 6). Tasks provide us the facility of handling cancellation and progress. 7).Example of Cancellation: class CancellationToken { public bool IsCancellationRequested{get; private set;} public void Cancel(){IsCancellationRequested = true;} public void ThrowIfCancellationRequested(); { If(IsCancellationRequired) Throw new OperationCancelledException(); } } 8). Example of cancellation using Task: var CancelResource = new CancellationTokenSource(); www.vuanswer.com www.vuanswer.com Task.Delay(5000).ContinueWith(ant=>CancellationSource.Cancel()); 9). Cancellation can even be used Task.Wait i.e. Synchronous methods but have to call cancel from another task. Cancellation is useful for timeouts. 10). In Task-Based Async Pattern (TAP) we create a “Hot” task From Task or TaskResult. 11). Task Combinator: Task WinningTask – await Task.WhenAny Console.WriteLine(“Done”); Console.WriteLine(WinningTask.Result); (Delay1(), Delay2(), Delay3()); int answer = await await Task.WhenAny(Delay1(), Delay2(), Delay3()); 12). Async call Graph execution:  brief sync execution on thread calling Go  Every await and return  when delay fires a thread  remaining statements run  eventually Go’s task is marked as completed. 13). Pseudo Concurrency means a program is running and awaiting for something then resuming and then awaiting. 14). Task Combinator uses Task.WhenAny and Task.WhenAll. www.vuanswer.com www.vuanswer.com Chapter NO.36 Short Notes 1). Example of WhenAll in Task Combinators: await Task.WhenAll(Delay1(), Delay2(), Delay3()); Task task1 = Delay1(), task2 = Delay2(), task3 = Delay3(); await task1(); await task2; await task3; Task task1 = Task.Run(()=>{throw null;}); Task task2 = Task.Run(()=>{throw null;}); Task all = Task.WhenAll(task1, task2); try{await all;} catch { Console.WriteLine(all.Exception.InnerExceptions.Count); } 2). there are two types of parallelism:  Data Parallelism  Task Parallelism 3). Three steps of Parallelism:  Partition Problem  Process  Combine the results 4). Data Parallelism is easier to perform and scales well, it is also structured. 5). Concurrent collections are useful when you want a thread-safe collection. 6). Tasks provide us the facility of handling cancellation and progress. 7). Three static method of the parallel class are:  Parallel.Invoke  Parallel.For  Parallel.ForEach www.vuanswer.com www.vuanswer.com 8). Parallel.Invoke: Executes an array of delegates in parallel. 9). Example of Parallel.Invoke: public static void Invoke(params Action[] actions); Parallel.Invoke( ()=>new WebClient().DownloadFile(“http://www.linqpad.net”, “lp.html”), ()=>new WebClient().DownloadFile( http://www.jaon.dk, “jaon.html”)); 10).Example of Parallel.For: for(int i=0; ifoo(i)); Parallel.For(0, 100, foo); 11). Example of Parallel.ForEach(): Foreach(char c in “Hello World) foo(c); Parallel.Foreach(“Hello, World”, foo); 12). ParallelLoopState is a thing which allows you to Break out of loops. 13). The ParallelLoopState class and its methids are: public class ParallelLoopState { public void Break(); public void stop(); public bool IsExceptional{get;} public bool IsStopped{get;} public long LowestBreakIteration{get;} public bool ShouldExitCurrentIteration{get;} } 14). Concurrent Collections are three times slower than normal collections in writing but not the case with reading. 15). Concurrent Collections include :  Concurrent Stack  Concurrent Queue  Concurrent Bag  Concurrent Dictionary www.vuanswer.com www.vuanswer.com 16). A Producer Consumer Queue: www.vuanswer.com www.vuanswer.com Chapter NO.37 Short Notes 1). HTML is a Hyper Text Markup Language 2). Java Script is built-in all platforms and is supported by all web-browsers. 3). Web pages have three kinds of layers:  HTML: Gives content/structure  CSS: Presentation Layer  Java script: Behavioral Layer 4). JS was introduced in 1995, originally named with LiveScript but got populated with most hot name “Java”, MS introduced jScript... their version of JS for IE, 5). JQuery: JS is a prog language... can be hard for some... also browser incompatibilities make testing difficult jQuery is a JS library intended to make JS programming easier jQuery soles JS complexity and browser incompatibilities can do things in single LOC that would take hundreds many advanced features come as jQuery plugins used on millions of websites 6). In HTML: at least three tags... html root tag, head tag containing title etc, and body tag containing all parts to be rendered in browser window is paragraph is emphasis is a hyperlink... XML attribute and value validating html means checking if all tags appropriately closed etc. 7). HTML Example: www.vuanswer.com www.vuanswer.com 8). CSS stands for Cascading Style Sheets, it is a formatting language 9). CSS says that take “this” and make “this” look like “that 10).JQuery says that take “this” and act like “that” 11). CSS can do more powerful stuff, like add border, change margins, and even control exact placement on web page 12). JS can add/remove/change CSS properties based on input or mouse clicks... even animate from one property to another... like yellow to red... or animate across screen by changing position 13). Example of CSS Style: Explanation: www.vuanswer.com www.vuanswer.com 14). Concurrent Collections are three times slower than normal collections in writing but not the case with reading. 15). JS is an interpreted language means each line of code is compiled at run time. 16). Tell Web Browser about JS by using tag 17). Using Script in HTML $.01: 18). Using Script in HTML 5: 19). Writing Hello World in HTML: 20). Basics of JS: www.vuanswer.com www.vuanswer.com lot of basic syntax like C++, C# create a variable using “var x”, names begin with letter, $, or _ var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']; alert(days); // Accessing element of array var playList = []; // Declaring empty array var prefs = [1, 223, 'www.oreilly.com', false]; //Array having different data types// prefs.push('test'); prefs.push('test',’test2’);... arrays grow prefs.unshift('test'); prefs.unshift('test',’test2’);... insert at start shift() gets/removes the first element... queue using push/shift pop() removes last... stack 21). Declaring Function in JS:  There is no specified return type  Function Declaration… no type 22). JQuery: many JS programs select elements, add new content, hide and show content, modify tag’s attributes, determine value of form fields, and react to user actions the details complicated specially with browser interoperability libraries offer a set of functions to make these tasks easy 23). Benefits of JQuery: only 30k compressed library size easy to learn used on millions of sites free dev community plugins... !!! www.vuanswer.com www.vuanswer.com Chapter NO.38 Short Notes 1). DOM stands for Document Object Model 2). Selection By element ID: document.GetElementById(‘banner’); 3). Selection By element name: document.GetElementByName(‘a’); 4). Basic Selectors are:  By Class Name  By ID Name  By Tag Name 5). Example of Select by ID: $(#banner) is the tag with id banner 6). Advanced Selectors are as follows: 7). Descendent Selectors: $(‘#navbar a’): select all the elements whose id is navbar then descendent a. 8). Child Selector: $(‘body>p’): Select p tags which are within body tag 9). Adjacent Sibling: $(‘h2+div’): Select tag “div” that comes immediately after “h2” tag. 10). Attribute Selectors :  $(‘img[alt]’): we need those images in which attribute of “alt” exists  $(‘input[type = “text”]’): we need all input fields of type text  $(‘a[href^=”mailto:”]’): we need tags whose link “href” starts with “mailto”  $(‘a[href $= “.pdf”]’): we need all that tags whose links are of “.pdf” type www.vuanswer.com www.vuanswer.com  $(‘a[href *= “missingmanual.com”]’): we need tags with “href” having string “missingmanual.com” 11). JQuery Filters: :even :odd $('.striped tr:even'): we need those rows on which class.stripped is applied :first :last :not $('a:not(.navButton)'): We need all the links that do not have.navButton class on them :has $('li:has(a)') --- diff from descendent : we need all these list items in which tag(a) exists :contains $('a:contains(Click Me!)') : we need that list in which the text “Click Me!” exists. :hidden :visible $('div:hidden').show(): find all div tags that are hidden and call.show() and they will show 12). JQuery Provides automatic looping 13). Automatic Looping: $('#slideshow img').hide(): Slideshow id containing all img tag choose them and hide them 14). Chaining Functions: $('#popUp').width(300).height(300): pop ID tag selected set width 300 and height 300 $('#popUp').width(300).height(300).text('Hi!').fadeIn(1000); 14). Concurrent Collections are three times slower than normal collections in writing but not the case with reading. 15). JS is an interpreted language means each line of code is compiled at run time. 16). Tell Web Browser about JS by using tag 17). Using Script in HTML $.01: www.vuanswer.com www.vuanswer.com 18). Using Script in HTML 5: 19). Writing Hello World in HTML: 20). Basics of JS: lot of basic syntax like C++, C# create a variable using “var x”, names begin with letter, $, or _ var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']; alert(days); // Accessing element of array var playList = []; // Declaring empty array var prefs = [1, 223, 'www.oreilly.com', false]; //Array having different data types// prefs.push('test'); prefs.push('test',’test2’);... arrays grow www.vuanswer.com www.vuanswer.com prefs.unshift('test'); prefs.unshift('test',’test2’);... insert at start shift() gets/removes the first element... queue using push/shift pop() removes last... stack 21). Declaring Function in JS:  There is no specified return type  Function Declaration… no type 22). JQuery: many JS programs select elements, add new content, hide and show content, modify tag’s attributes, determine value of form fields, and react to user actions the details complicated specially with browser interoperability libraries offer a set of functions to make these tasks easy 23). Benefits of JQuery: only 30k compressed library size easy to learn used on millions of sites free dev community plugins... !!! 24). Attributes can be manipulated with  addclass  removeclass  toggleclass 25). Example of multiple css Properties 26). Explanation of above code: www.vuanswer.com www.vuanswer.com 27). When acting on each element in selection key word Each is used like this: 28). Web mouse Events are : click, dblclick, mousedown, 29). Doc/Window Events: load, resize, scroll, unload 30). Form Events: submit, reset, change, focus, blur 31). Keyboard Events: keypress (over n over), keydown, keyup 32). Steps in setting Events: step 1: select elements step 2: assign an event step 3: pass function to event $('#menu').mouseover(function() { $('#submenu').show(); }); // end mouseover 33). Examples of Events: www.vuanswer.com www.vuanswer.com 34).JQuery Events: hover toggle is like hover except worked on and off by clicks event object is passed to all functions handling events www.vuanswer.com www.vuanswer.com www.vuanswer.com www.vuanswer.com Chapter NO.39 Short Notes 1). Web events also have an event object just like desktop event object. 2). ent.PreventDeafult() or return false to stop the default behavior. 3). For removing enet us: $(‘.tabbutton’).unbind(‘click’) 4). For stopping default event bubbling: evt.StopPropagation() 5). Generic way to bind events: $(‘#selector’).bind(‘click’, mydata, functionname) 6). Event Properties: 7). Examples: Binding multiple events: www.vuanswer.com www.vuanswer.com 8). FAQ Example: 9). JQuery Animations: $('element').fadeOut('slow'); fast normal slow or number of ms default 200 400 600 fadeIn, fadeOut, fadeToggle slideDown, slideUp, slideToggle 10). Example of Login Slider: 11). Forms: www.vuanswer.com www.vuanswer.com var unitcost = 9.95; var amount =\$(‘\#quantity’).val(); var total = amount*unitcost; total = total.ToFixed(2); \$(‘\#total’).val(total); 12). JQuery Form selectors: www.vuanswer.com www.vuanswer.com Chapter NO.40 Short Notes 1). Ajax is a term which allows us to talk to server remaining within JS. 2). What Ajax can do:  Display new HTML content without reloading the page  Submit form and instantly display the result  Login without leaving the page  Ajax make pages feel more responsive and Desktop like 3). JS, server-side programming, and web browser, all work together 4). Role of Java Script in Ajax:  Send Request  Wait for response  Process Response  Update Web Page 5). Role of Web Server: Receive Request Respond as HTML, plain text, JASON 6).XMLHttpRequest is also known as XHR in short 7). Steps (Talking to Web Server)  create XMLHttpRequest (also called XHR in short) var newXHR = new XMLHttpRequest();  call open to specify what kind of data and where it will go can GET or POST newXHR.open('GET', 'shop.php?productID=34');  write a callback function it will remove, add, change elements  send data newXHR.send(null); GET www.vuanswer.com www.vuanswer.com newXHR.send('q=javascript'); POST  receive response callback invoked and XHR receives status, text response, and possibly an XML response 8). The basic concept of POST is that if you want to post a lot of data then instead of sending it via URL you can insert this into the request body. 9). The Web Server Request can respond in the following states: status = 200/304 all ok, 404 file not found, 500 internal server error, 403 access forbidden 8). The JQuery simplifies all steps except that of changing the webpage 9). Example of loading news in a div from web-server using jQuery: $('#headlines').load('todays_news.html'); 10). Get() and Post() in jQuery: need server side to do anything else server may not return html e.g. database records as xml or json jQuery handles differences of GET and POST $.get(url, data, callback); $.post(url, data, callback); 11). Examples of using Get() and Post(): GET has limit... often thousands of chars $.get('rateMovie.php','rating=5'); $.post('rateMovie.php','rating=5'); $.post('rateMovie.php','rating=5&user=Bob'); 'favFood=Mac & Cheese' // incorrect 'favFood=Mac%20%26%20Cheese' // properly escaped var queryString = 'favFood=' + encodeURIComponent('Mac & Cheese'); $.post('foodChoice.php', queryString); 12). The better way to use Get() and Post() is object literal i.e. var data = $.post('rankMovie.php', { rating: 5, user: 'Bob' } ); // end post www.vuanswer.com www.vuanswer.com 13). Serialize is used for form submission in JS by so that the page may not reload. 14). Example of using serialize method: var formData = $('#login').serialize(); $.get('login.php',formData,loginResults); 15). third parameter in get() and post() is call back. We write a function that will process data returned by server. 16). Example of Processing Returned Data: 17). php is a server side programming language. 18). Error Handlers: $.get(url, data, successFunction).error(errorFunction); $.get('rate.php', querystring, processResponse).error(errorResponse); function errorResponse() { var errorMsg = "Your vote could not be processed right now."; errorMsg += "Please try again later."; $('#message').html(errorMsg); } 19). JASON: JS format... method for exchanging data JSON is JS so its quick n easy for JS no XML like parsing JSON is a JS obj literal { firstName: 'Frank', lastName: 'Smith', phone: '503-555-1212' } OR www.vuanswer.com www.vuanswer.com { 'firstName': 'Frank', 'lastName': 'Smith', 'phone': '503-555-1212' } (MUST use if names have spaces etc.) server returns a string formatted like a JSON obj literal jQuery getJSON method like get but data passed to callback will be a JSON object e.g. var bday = { person: 'Raoul', date: '10/27/1980' }; bday.person // 'Raoul' bday.date // '10/27/1980' www.vuanswer.com

Use Quizgecko on...
Browser
Browser