How to Read Api Documentation for Jquery Ui

Read Time: 45 mins Languages:

In this Nettuts+ tutorial, nosotros are going to larn how to create a dynamic content editing system using the jQuery UI Widget Manufacturing plant. We'll get over how to develop a logical, object orientated jQuery UI Widget, transform various nodes to editable text fields, delegate events within the widget framework, manage context, toggle icons, serialize data, and of class edit, restore and delete data using jQuery's fantastic AJAX functionality!



Creating a Widget Blueprint

The first thing nosotros'll do is set up a blueprint for our widget which we'll name "editable" and whose namespace will be "ui". The widget's proper name will be the first argument when calling the widget mill method. The 2d argument volition be an object literal containing the various properties and methods for the widget itself. It's a very simple, make clean and efficient way to churn out plug-ins. There are a number of inherent props and methods to a UI widget. We'll be using the following vanilla $.widget props:

  • Options{...}

    This object literal is the only property of our widget that will exist exposed to users. Here, users volition be able to laissez passer their own arguments to the widget which will, of grade, override any default options we specify. Examples include callbacks, element selectors, element classes etc.

  • _Create()

    This is the commencement method called during the widgets initialization and information technology'south only called one time. This is our "set" method, where we'll create / manipulate elements in the DOM as well as bind event handlers.

  • _Destroy()

    This method is the only our widget's but public method in that users can specify "destroy" equally an statement to calling the widget. This method is used to tear downwardly / destroy an instantiated widget. For case, nosotros'll be using destroy to remove whatsoever HTML generated by our widget, unbind event handlers and of course, to destroy the instance of the widget relative to the element information technology was called on.

Here's What We'll Be Using:

Take notation of the underscore which precedes the _create method. Underscores denote a private / internal method which is not accessible from outside the widget.

For more than information on UI Widget development, equally well as the other inherent methods such as _trigger(), _getData(), _setData() and so you lot can check the following great resources:

  • jQuery UI Widget Factory Evolution Wiki
  • jQuery UI API Developer Guide
  • Tips for Developing jQuery UI 1.8 Widgets by Eric Hynds
  • jQuery UI Widget upgrade guide for jQuery ane.eight
  • jQuery Forums - A groovy postal service past Richard D. Worth, Project Lead for the jQuery UI and a brilliant developer, contrasting and explaining the _init and _create, methods and their uses.

Brainstorming: What Methods Do We Need? What Does Our Widget Need to Do?

As we're creating a content editing widget we'll apparently need some manner to edit content. Additionally, we'll want the ability to delete content as well as abolish revisions. We'll also need "edit" triggers, say icons which, when clicked, volition toggle the land of our content as well as toggle state between default and editor icons. With this functionality in mind, let's define some general methods at present:

  • _CreateEditor()

    Typically, information technology's good to split up logic in a logical, clean easy to read manner. Although nigh of the DOM creation and insertion can be washed within the _create() method itself, since we'll be creating editors for multiple sets of content (i.due east. table rows) allow's utilize an independent method which nosotros can phone call from a for loop! The _createEditor() volition be called to handle the cosmos and insertion of the core editor elements. This separation of logic should make the widget easier to empathize at a glance as well as help us maintain our lawmaking down the road.

  • _ClickHandler()

    This method speaks for itself, it's the handler which volition exist used when the user clicks on ane of our "editor" icons. Although nosotros could demark a handler to each private icon type let'southward simply use a single handler and a instance switch to telephone call appropriate methods based on which icon was clicked. There are minor benefits and drawbacks to bounden a single handler for all icons and individual handlers for each icons so it'due south actually simply a matter of preference and performance.

  • _ShowIconSet()

    This is the method will be used to change our icons from their "default" state to their "editor" country. As mentioned above, we'll desire the ability to edit / delete an detail as well as save / cancel changes. We only need to brandish 2 icons at whatsoever given fourth dimension (edit/remove and salvage/cancel, respectively) and so this method will toggle our icons betwixt those ii states.

  • _TransformElements()

    Here'south where the core logic of transforming elements back and forth from their original state to editable fields takes and vice versa. This method will exist used when we make elements editable, save changes or cancel a modify. This method will also exist responsible for populating / repopulating the element / input with the relevant text.

  • _RemoveElements()

    This method will be responsible for removing elements from the DOM when an detail is deleted by the user.

  • _Encode()

    As we'll be saving / deleting data with jQuery's powerful AJAX functionality, we'll need a way to convert these text nodes and class inputs, along with their corresponding "field names", into a standard URL-encoded string. As such, this method will handle the serialization of text / input values.

  • _Post()

    This method will handle all of our AJAX logic. It will be responsible for both saving and deleting data and it's callbacks volition be used to update the DOM when appropriate. Additionally, any user divers AJAX callbacks will be fired from here every bit well.

Here'southward a Look at Our Widget's Blueprint Then Far:

Above, detect that nigh all of our methods are preceded with an underscore. The underscore denotes a individual method which means that whatsoever property or method preceded by an underscore will not be accessible from outside the widget. There's not much demand to make any of our methods public, so we'll proceed them with an underscore.


Full Screencast



Options, Options and More Options!


Now, let's ascertain some user overridable options for our widget! This is e'er a fun stride as there are a plethora of really interesting and smashing things that tin can be washed here. For instance, creating callbacks. Nosotros tin create optional callbacks for virtually anything, saving data, deleting data, errors, success, completion, events etc. Additionally, we can easily define the context of these callbacks. So, want to animate the color of a row subsequently a successful update? No problem! Want to have each field blink in rapid succession as a visual confirmation? Easy equally pie! This, for me, is one the near fun and powerful features of any given widget. The ability to mold information technology'south functionality and interactivity to adapt the users needs.

Additionally, nosotros'll also be defining some of import cadre options such a selector for those elements we want to make editable, where we desire to insert our icons, custom class names as well as some other AJAX options. Here's a look at our options which is an object literal:


Some General Options

Here, nosotros'll define some core options for our widget such as chemical element selectors, form names, field names and so on...

  • Elements:

    This will exist a selector string for those elements we want to make editable. Nosotros'll utilize a selector for table cell elements "td" every bit the default selector. This can be overridden, though. Whatever valid jQuery selector string would work. For example:

    • "td"
    • "td>small"
    • ".editable-content"
    • ".editable p"
    • "div:has(p)"

    For more data on jQuery selectors, see the jQuery Selectors API

  • elementParent:

    Hither, we'll permit the user to define a selector which volition server as the parent container for sets of editable content. Yous could virtually retrieve of this as sort of pseudo fieldset used to group inputs together or even a tabular array row which groups cells together. This is useful if the user wants to make something other than tabular array rows editable.

    As such, this selector is very of import. We'll be looping through each elementParent while creating, appending, binding, and caching elements! Every bit with the elements belongings, any valid jQuery selector will work here within the context of the element upon which the widget was called. As a default value, we'll use tbody tr to select all of the table rows within the table body.

    Note: In case your wondering why we don't specify the parent container by doing something like this:

    Consider that the immediate parent of the element may not be the common parent of all the editable nodes for a given row / block. What if the nodes were editing are nested within another chemical element? Past specifying an implicit parent container we know that we are dealing, specifically, with the appropriate top level container for all of the editable content within a given row / block.

  • insertMethod:

    Here, we'll allow the user to define which jQuery insert method volition be used for appending the icons and their container. A valid jQuery insert method cord, such every bit appendTo, prependTo, insertBefore or insertAfter should exist specified here. The default insert method will be appendTo.

  • Classes:

    Allowing the user to specify their own / boosted grade names opens upward a slew of new possibilities such as using a css framework, like the jQuery UI CSS Framework, or peradventure icon classes from an paradigm sprite they've created! Here, the user can specify additional grade names, every bit a string, for a number of different elements. We'll fix some default classes for the icons using jQuery UI Themeroller icon classes. So, classes will be an object literal with backdrop every bit follows:

    • iconContainer: A space separated cord representing boosted classes for the parent element of the icons
    • edit: A space separated string representing additional classes for the edit icon
    • remove: A space separated string representing additional classes for the remove icon
    • save: A infinite separated cord representing additional classes for the save icon
    • cancel: A space separated string representing additional classes for the cancel icon
    • th: A space separated string representing additional classes for the table header element which volition exist created conditionally

    For more information on the jQuery UI Themeroller CSS Framework see the jQuery UI Themeroller API every bit well equally the jQuery UI Themeroller

  • fieldNames:

    This option will be a simple assortment of representing the numerically indexed field names of the content which is being made editable. So, for example, if the editable content represents "terminal-name", "get-go-name" and "accost" fields, we would specify those field names in chronological order, the order in which these items are displayed in the DOM, from first to last, ["final-proper name","first-name""address"]. For instance:

    We'll initialize an empty array every bit the default value.

  • Action:

    This option will is an object literal used to specify the pseudo action belongings for our AJAX requests. In simpler terms, information technology will contain the url strings to which jQuery's $.ajax will submit. It will incorporate ii backdrop:

    • Edit:

      The url string used when editing content.

    • Remove:

      The url cord used when deleting content.

    As default values, nosotros'll use javascript'southward location.href holding which is the url of the current page:

  • ajaxType:

    This string will decide the type of $.ajax request we'll apply. The default method is is mail service but the user can specify something else should the need arise.


Callbacks

Hither, we'll define some empty functions / placeholders for user defined AJAX callbacks...

  • Create:

    This optional callback will be called at the stop of the _create method in the context of this.chemical element.

  • Destroy:

    This optional pre-callback will be called at the beginning of the destroy method as well in the context of this.element.

  • ajaxBefore:

    This optional callback will be called before an AJAX request begins in the context of the editable contents shared parent. This tin be used for a number of things, such as, for example, displaying an AJAX loader gif.

  • ajaxError:

    This optional callback will be chosen if there is an error in the AJAX request in the context of the editable contents shared parent. With this callback, you give some feedback back to the user letting them know that their post did non consummate.

  • ajaxSuccess:

    This optional callback will be called, again in the context of the editable contents shared parent, if there is AJAX call request successfully. This can, as above, be used for a number of different things such every bit letting the user know the request was a success.

  • ajaxComplete:

    This optional callback volition be called when AJAX request is complete - regardless of success or fault also in the context of the editable contents shared parent. This could, for example, be used to remove an AJAX loader gif signifying the asking is complete.


Let's Have a Look at the Widget Now That Nosotros Have Our Options Divers:


Creating, Appending, Binding and Caching With the _Create Method!


Having divers the blueprint of our widget, as well as it'southward options, our adjacent pace will exist to _create the widget itself! This method is called merely once, at the widgets initialization.

In the _create method, we'll kickoff ascertain a number of internal props (read: properties) to be used later, within the widget. Essentially, we'll be caching selectors and booleans as well as defining class names and such. Then, we'll proceed to element creation, insertion and caching besides as adding classes and binding an event handler.


Defining Some Properties

As mentioned above, the kickoff step in _create will be to define some backdrop. Let's get through them, ane at a time:

  • this._element:

    This property will be the jQuery selector representing the element which was used to instantiate the widget

  • this._table:

    This boolean holding will use a ternary operator to determine if this._element is a table. If this property evaluated to truthful, later on, nosotros'll create a table header chemical element so that the number of columns in the thead and tbody correspond.

    For more data on ternary / provisional operators come across the Mozilla Developer Network or MDN for brusk

    Note: Rather than using a ternary here we could have only used the "this._element.is('table')" expression equally it returns a boolean value. It's better to just enshroud the boolean here rather than repeatedly calling the is method. This is also a lot more readable.

  • this._elementParent:

    Using jQuery selector string from the options argument, nosotros'll cache a jQuery selector for the editable contents shared parent element within the context of this._element

  • this._editable:

    Here, we'll initialize an empty assortment which volition, shortly, be populated with jQuery collections of editable content relative to the alphabetize of their parent container. The array key volition direct correspond to the index of the parent element. In other words, _editable[0] will exist the jQuery drove of all editable content within _elementParent[0]. This is a nifty / speedy way to cache editable collections for utilize later on.

  • this._triggers:

    This will exist an object literal containing the "action" classes for our editor icons. I call them activeness classes equally these classes will be used to decide what action should be taken in our issue handler.

    In defining these classes, we'll apply another property provided by widget framework, this.widgetBaseClass. This belongings always returns a base class for the widget, which, in this case, will exist ui-editable.

    And so, essentially, we'll concatenate the widgetBaseClass with appropriate grade names for each of our icons. These triggers classes are independent of any other classes the icons may have. Although they may be used to style the icons with css, they are primarily used in our event handler.

    For more than information on string concatenation see the Mozilla Develops Network.

  • this._classes:

    Not unlike the _triggers property above, this._classes will too be an object literal of form names. The departure here is that _classes will contain a chain of predefined and user defined class names.

    Using a ternary operator, we'll concatenate base classes with whatever optional classes specified in the options.classes prop.


Adding Classes to the Editable Content

Now that we've divers a number of properties, nosotros're ready to add the appropriate class to our editable content.

This stride is as simple as uncomplicated can be. We'll use a jQuery selector for all of the editable content in the context of this._elementParent. We'll ascertain the selector with the cord given to united states of america in the options.elements argument. Then, using jQuery'southward addClass method, we'll add the class name we cached a moment ago in the _classes object.

For more information on jQuery's addClass method meet the jQuery API


Creating Our Editor and Binding Away!

The icons and their containers volition be created equally nosotros loop through our _elementParent drove.
In other words, each _elementParent will accept it's own set up of icons.
We'll also enshroud selectors, in context, for these icons, their container as well as the editable content relative to the electric current _elementParent in the loop.

  • A Few Variables for the Loop

    Before we being our for(){...} loop, nosotros'll initialize a variable for the initial expression, which is the iterator which is incremented is the loop. Nosotros'll then ascertain an integer representing how many elements are buried in the _elementParent collection, using jQuery's size method.

    For more information on for statements run into the Mozilla Developers Network
    For documentation of the jQuery size method see the jQuery API

  • Caching and Creating the Icons and Their Container:

    We'll be populating the empty _iconContainer array here past assigning the render value of the _createEditor method to it as a new prop, i. As you'll see, momentarily, _createEditor volition return the jQuery selector for the newly created icon container.

    And then, since i is the equal to the index of the current _elementParent in our loop, _iconContainer[i] will be the container for our icons within _elementParent[i] only!

    Every bit we iterate, we'll be using the iterator, i equally the array key for several jQuery collections including the _editable array, the _icons array too equally the _iconContainer array.

    Note: The array keys for the _editable, _iconContainer and _icons collections will always stand for to the index of the _elementParent in the current iteration of the for loop.

  • Caching an Editable Selector in Context

    In like manner to the _iconContainer array, we'll now cache a selector for all editable content in the context of _elementParent[i].

    We'll define the editable content's selector string by concatenating a . with the advisable course name stored in our _classes.editable prop.

  • Binding an Event Handler to Our Icons

    The last thing nosotros'll do in our for loop is bind a handler to the click event of our newly created icons. As were binding a handler within the context of a jQuery UI Widget / Object, we'll need to pay special attention here as the context of this in a typical jQuery effect handler, refers to the element which received the effect. This is one of jQuery's nicest features as it standardizes what this is across all browsers. (I'm lookin at you IE ;)

    And so, here are two unproblematic approaches to handling context inside a widget event handler.

    • event.information

      First and foremost, we can simply pass this instance of our widget to the handler as an effect.information argument which is provided by some of the diverse jQuery bind type methods. Essentially, the second argument, which proceeds the function call, tin exist an object literal of data we desire to laissez passer to the handler. In the handler, this data is accessible in the event object equally the issue.data property! Hither's how it looks:

      So, effect.information.widget will be a reference to our widget instance and event.data.i will exist a reference to our iterator!

      Passing an event.data argument is neat when you don't want to modify the context of this within your handler. Additionally, it doesn't require some other function call as the next method, $.proxy, does.

    • $.proxy()

      Equally stated in the jQuery API, "This method is most useful for attaching event handlers to an element where the context is pointing back to a different object."

      In other words, by proxying our widget to the handler, this will refer to our widget instance rather than the chemical element which received the outcome.

      Fifty-fifty though the target chemical element would no longer be assigned to this, it would all the same exist attainable in jQuery's event object as the event.target property. Equally many developers are already in the addiction of caching a selector for $(this) in event handlers, it wouldn't be to much of a stretch to cache an $(event.target) selector instead.

      Without further adieu, here'southward the $.proxy method in action:

  • Binding a handler using the event.data statement

    With an agreement of both event.data and $.proxy, permit's employ the event.data argument to pass our widget and iterator forth to the handler.

Permit's accept a look at the logic of our for loop now, in its entirety:


What Nigh Table Headers?

With the icons created, inserted and bound we'll need to brand a minor aligning if this.chemical element is a table.

Although nosotros haven't divers the _createEditor method all the same, the blazon of icon container element it creates is relative to what this.element is.

So, if were working for a tabular array, it will create a td and append it to the table. If were working any other blazon of element, it will create a div.

Equally such, appending another td to a tabular array row leaves us with an incomplete table caput equally there will be more tables cells in the torso than at that place are table headers in the head.

Then, we'll need bank check if this.chemical element is a table or not and if information technology is we'll create, populate and append, using the insertMethod specified in the options argument, a th element. Although creating DOM elements with jQuery is simple and clean I sometimes like to write it out in obviously javascript. Permit'due south take a look at the logic:

  • Checking for a Table

    First, we'll check our table property which, equally you may remember, is a boolean representing whether or not this.element is a table.

  • Information technology It'due south a Table, Create a Header!

    If this.chemical element is a table, we'll demand to create and append a new th to the tabular array head's offset and hopefully just table row, here'south how we'll practise it:

    • Creating the table header

      If this.element is a table, we'll create a new th element equally the variable th.

    • Giving it some class!

      Next, we'll ready the className property for this element as the tableHeader class name specified in the _classes object.

    • Setting the innerHTML of the the table header

      Then, we'll set the innerHtml, which in this case is just text, of this element.

    • How about a little style?

      We'll specify one css rule, text-marshal as center. This volition eye the header text and look prissy as the icons themselves volition also exist centered via css.

    • Appending the table header to the tabular array head

      Lastly, using the jQuery insertMethod specified past the user, nosotros'll dynamically insert the element into the tabular array header of our table. Have note of our DOM insertion:

      Did you notice that we have our insert method in foursquare brackets correct after the jQuery selector?

      You may exist wondering what this is or how it works. Basically, think of jQuery as one big (awesome) object. As an object, you can use associative array / square bracket style note with it! This shorthand allows us a peachy deal of flexibility in calling methods dynamically based on relative weather!


How About a Callback!

The last thing nosotros'll do in the _create method is phone call the user divers create callback if it'southward been specified.

In that location are a plethora of reasons to use a callback in the _cerate method. Here'south one case!

Let'southward say the user, with a success callback, is changing the color of tabular array cells to reflect a successful update. Should the widget exist destroyed, they'll need some way to restore the colour of their table cells. Of course, they could implicitly set the colour manually in the destroy callback simply how about saving the tabular array jail cell color using jQuery'south $.information method which is a much more than dynamic approach! That information would be attached to this.element equally that will exist the context of our callback.

Thus, when the widget is destroyed, the user could simply gear up the colour back to it's default value by accessing the appropriate $.data

Widget Callbacks Explained

Every bit user defined callbacks are optional, their default values will always be fix to null.

As such, we'll employ jQuery'south isFunction method to decide if the callback's blazon is function and and so call it if information technology is.

Alternately, nosotros could apply javascript's native typeof operator to determine if the typeof callback is a role. Nosotros'd have to enclose the typeof operator in parens so that nosotros could have information technology'southward return value and convert information technology lower case, using javascript's native toLowerCase method, and then as to standardize the output. Information technology'due south much simpler, though, to use jQuery's isFunction method but here's a expect at this technique in vanilla javascript:

Here'south the how we'll exercise it with jQuery:

So, if the callback is a role, we'll execute information technology using javascript's native telephone call method.

The phone call method allows us to specify the context of our callbacks. In other words, it will define what this refers to within the callback part.

As such, we'll utilize this.chemical element as the context here which will define this as the the element to which our widget was instantiated.


Within the _createEditor Method


In the previous department we discovered the logic of how we'll create elements. Now, allow'due south a have a look at the implementation. The _createEditor method will exist called from within the _create methods for loop to do all the element creation and insertion relative to the index of the current _elementParent in the loop.


Arguments

The _createEditor method takes one argument, i, which is equal to the alphabetize of the current _elementParent from the _create methods for loop.


Initializing a Few Variables

The first affair we'll exercise here is initialize a few variables which we'll use in our chemical element creation. We'll a initialize a variables for the edit icon as well as the remove icon.


Creating Our Icons

With these variables initialized, permit's go ahead and create our icons using some elementary javascript! Essentially, we'll utilise the same techniques as we used for the conditional table header but with one exception. Rather than setting the innerHtml of the link we're creating, we'll be setting the championship attribute instead. This manner, on mouseover, the user we'll come across a tooltip description of what the icon does! Here's a look at our anchor / icon creation:


Creating the Icon Container

With the icons prepare to go, nosotros'll need to create a container for them. The element blazon of this container will depend on whether or not we're working with a table. So, using the _table boolean nosotros divers in the _create method and a ternary operator we'll create a td chemical element if nosotros're working with a table and div element if we're working with anything else. Then, we'll set the container'due south className using the _iconContainer class we defined in the _classes object.


Caching a Selector for Our Icons

We'll now brainstorm populating the _icons assortment with a jQuery selector for the newly created icons, we'll pass these icons along as an array.

The array key for this collection will be i, thus _icons[i] will correspond all of the icons contained in _elementParent[i].


Returning the Icon Container Afterward Setting Its HTML and Appending It to the DOM

At present, nosotros'll chain a few jQuery methods together in order to set the html of _iconContainer[i] and suspend it to the DOM.

First, using jQuery'south html method, we'll set the html of the _iconContainer[i] to this._icons[i].

Next, with our icons appended to the _iconContainer[i], we'll append it to the DOM, dynamically, using the options.insertMethod string in square subclass / associative assortment notation.

Lastly, as most jQuery methods return the bodily jQuery selector existence used in the expression itself, this expression volition return $(iconContainer[i]).

Thus, this._iconContainer[i] which is existence defined in the _create method's for loop, will equal $(iconContainer[i]).

For more than information on returning values from a function, check the Mozilla Developers Network

Documentation of the jQuery html method can be found in the jQuery API


Our Widget'south Event Handler, the _ClickHandler Method


With our widget instantiated and set to go information technology's at present time to handle it'south beliefs. The logic of this widget is such that the click handler volition serve as a sort of "controller" in that it volition determine what action is to be taken based on the class of the icon which received the click.

In other words, if the users clicks an edit icon, the handler volition bank check the icons form and and so telephone call the advisable edit functionality of the widget, and so on...


Arguments

The _clickHandler method takes one statement, event. By specifying an empty statement here, jQuery volition automatically assign the event object to this statement. The event object contains a number of very useful properties such every bit target, timeStamp, preventDefault and stopPropagation to proper noun a few. Nosotros'll exist using a couple of these props / methods in our event handler.


Preventing Default Behavior

The commencement affair we'll do in our event handler is call the preventDefault method of the jQuery event object. This method volition prevent any default actions from occurring every bit a outcome of the event. What this means for the states is that when a user clicks one of the icons, which is really an anchor, preventDefault will cease any blazon of navigation / scrolling from being triggered - pretty dandy eh?


Defining a Few Variables

Get-go, we'll cache a jQuery selector for this, which is, of form, the element which received the outcome.

Adjacent, nosotros'll define the variable i which was passed to our handler in upshot.data This was the iterator used in the _create method'due south for loop to cache selectors for various elements relative to _elementParent[i].

We'll then define the variable widget by assigning evet.information.widget to it which is a reference to the current instance of our widget.

Now, nosotros'll ascertain a sort of shortcut variable, triggers as the widget._triggers holding. This property contains all of our icons trigger classes which we'll exist using to determine what deportment to accept.

Lastly, we'll initialize the variables, information and inputs. These vars volition only exist used when we need to serialize data for AJAX requests.


Determining What to Do With a Case Switch

The switch statement is very much like an if statement in that it evaluates an expression and simply executes certain code if the status is met. In some circumstance, it may exist cleaner / easier to read. There are, even so, various benefits and drawbacks to either statement but either would be advisable given the proper weather condition.

We'll exist evaluating four weather based on the switch statements label which nosotros'll set up as true. We are going to bank check the icon's grade using jQuery'southward hasClass method which returns a boolean. If the icon has the class name specified in the argument, it will return true.

Equally you can run across, this a clean, readable way to evaluate which icon was clicked. Obviously, there are a number of different ways to exercise this and an if statement would piece of work merely as well. Now, let's have a closer look at each case and what we'll be doing!

  • The Edit Icon

    If the edit icon has been clicked we need to, outset, toggle the default icons, which are "Edit" and "Remove" to the editor icons which are "Save" and "Cancel". So nosotros'll call the _showIconSet method.

    You lot may recollect this method from the widget blueprint we created earlier. Although we haven't defined it however, it takes two arguments, i which will be used to select the icons we'll toggle and editor. The editor statement specifies which iconset to prove, default or editor.

    In one case we divers more of our widget's methods, you'll see that most of them autumn into line with jQuery in that they usually return this. As a result, we chain most of these methods together. Then, let's add another method to this expression, transformElements.

    transformElements is sort of a workhorse in that it's responsible for making content editable, restoring content to it'southward previous country as well equally updating content that'south been edited. This method takes two arguments too, i, which, once more, we'll be used to select the appropriate _editable drove and i, blazon which will define the blazon of "transformation". Here's a wait:

  • The Remove Icon

    If the remove icon has been clicked, we'll need to remove this editable content both from the DOM as well as from the database.

    We volition, of form, be using an AJAX request to delete this detail from the database just since we're not submitting a form here and we don't really have whatsoever inputs, which are automatically serialized on submission, nosotros'll need a way to serialize / encode the text of these elements into a valid url string.

    So, nosotros'll phone call our widget'due south _encode method to serialize this data. We'll laissez passer i argument to _encode, the jQuery selector for the elements to be removed. _encode volition serialize the text of those elements for u.s.a. and return the a valid url string. And so, we'll define the variable data as this value.

    Lastly, nosotros'll call our widget's _post method which will submit an AJAX request to the server. We'll laissez passer 3 arguments to _post, the serialized data, a variable which indicates whether we're saving or deleting data and i, which will be used in the $.ajax success callback to actually remove the deleted elements from the DOM.

  • The Save Icon

    If the save icon was clicked, we'll need to serialize our inputs, as nosotros did above, using the _serialize method. So, nosotros'll need to phone call our widget'due south postal service method in order to submit the AJAX request to the server.

    Every bit such, we'll define ii variables here, inputs and information. inputs will be defined as the jQuery collection of inputs within the context of this element and information will be the return value from the _encode method, just as to a higher place.

    Finally, we'll telephone call the _post method with it'south three arguments, the serialized data, the type of post we're making (in this case, "save") and i which is used in the $.ajax success callback to update the appropriate elements in the DOM.

  • The Cancel Icon

    Finally, if the cancel icon has been clicked, nosotros'll restore the icons and editable content back to their default states.

    To do this, we'll first call the _showIconSet method with two arguments, i and default. i volition exist used to select the appropriate drove from our _icons assortment and default specifies which icon set to show.

    Adjacent, we'll chain the _transformElements method to this expression with one argument, i, which, every bit usual, is used to select the appropriate collection from our _editable array.

    Note: If you're not exactly sure as to what's going on in the methods nosotros're calling, it'southward ok. We haven't defined these methods yet and so there'south no reason you really should empathize yet. Hang tight, we'll be defining these methods shortly.

  • The Total Switch Argument


That'southward It for the Click!

Hither's how the complete _clickHandler method looks at present that nosotros've defined it:


Toggling the Icons To and Fro!


In our upshot handler, we telephone call the _showIconSet method whenever we need to toggle icon state betwixt editor and default. This is the method responsible for making those changes.


The _showIconSet method, step by step!

Taking advantage of jQuery'south awesome chaining adequacy, allow'southward take a look at how we tin can alter icon state with merely one variable and statement!

  • Var Titles

    Showtime off, were going to ascertain a new variable, titles as an array, using a ternary operator.

    This variable volition incorporate the title attributes for our icons.

    We'll bank check the iconSet argument to make up one's mind which icons nosotros're displaying and the populate the array with the appropriate titles accordingly.

  • this._icons[i]

    Now, using i nosotros'll select the appropriate element drove from our _icons array.

  • Eq(0)

    The eq method is used every bit a filter confronting a jQuery collection in that information technology returns the chemical element with the specified index. Thus, calling eq(0)in the context of _icons[i] method will narrow our selection down to the icon with an index of 0 inside that collection. In other words, the offset icon.

    For more than information on jQuery'southward eq method check the jQuery API

  • toggleClass()

    Using jQuery's toggleClass method, we'll add and remove classes to our icons, respectively. So, if a specified class is nowadays, it will be removed. Conversely, if a specified class is not nowadays, it will exist added.

    We'll concatenate the advisable classes for each icon with a space as the toggleClass method accepts multiple grade names every bit a space separated list. Pretty nifty!

    Documentation for jQuery's toggleClass method can be found in the jQuery API

  • Attr('title', Titles[0])

    With our commencement icon's classes now set up, nosotros'll define it's title attribute using the jQuery attr method. We'll set the championship using the appropriate value stored in the title array we created just a moment ago. The array keys for the championship array match the index of the icon currently selected so the title for this icon is bachelor every bit titles[0].

    To read upwards on jQuery's attr method, bank check the jQuery API

  • Finish()

    jQuery's terminate method is used to remove the almost recent filter practical to a collection. By calling finish hither, we'll be removing the eq filter from our collection. In other words, we'll exist working with _icons[i] again.

    Documentation for jQuery'south stop method tin can be found in the jQuery API

  • ... the Side by side Verse Same every bit the Showtime!

    We'll use jQuery'south eq method again to specify the second icon at present. The second icon volition have an index of one, since indicies are zero based, and as such we'll use eq(ane) to select it.

    Post-obit suite with the higher up expression, we'll u.s.a. the exact same methods for the second icon as nosotros did for the first only with the advisable class names and title.

  • Return This

    The terminal thing we'll practise here is return this so every bit not to break this methods chainability.


VoilĂ !

Now that nosotros've defined our variable and expression, permit's take look at the unabridged _showIconSet method at present:


_transformElements: The workhorse method!


In this method, we'll be looping through the editable content in club to get / set an advisable text / html string for that element relative to the type of transformation nosotros're making. Then, we'll simply ready the element's html.

After the loop, as usual, nosotros'll return this!


Arguments

This method takes two arguments, i and blazon.

i, will exist used to select the appropriate jQuery collection from the _editable assortment relative to _iconContainer[i] from the _create method.

The blazon argument simply specifies the type of transformation that's being called. This method handles 3 three types of "transformation":

  • Making content editable and storing electric current values for possible retrieval
  • Restoring editable content dorsum to its default state with it'south original values
  • Restoring editable content back to its default state with new values

As such, type volition either be "edit", "restore" or "update".


A Necessary Shortcut...

First off, we'll need to ascertain a variable which references the options.fieldNames array.

It'due south necessary to ascertain this reference within the context of this method so that it will be available to the inner function, $.each, we'll be calling presently.

The fieldNames var will simply be used when making elements editable.


Iterating Through Our Editable Content

Using jQuery's $.each method, we'll iterate through _editable[i]. Nosotros'll pass the empty argument, alphabetize, to $.each. The numeric index of each chemical element in the loop will be assigned to this argument.


Variables Within the $.each Method

Inside the telescopic of $.each, we'll ascertain / initialize two more than variables respectively:

  • Html:

    Well initialize the html variable, here, in the scope of $.each. This var will comprise an html string if we're making content editable and a text string if we're updating or restoring content.

  • Self:

    Nosotros'll cache the jQuery selector for this, the selector for the current element in the loop.


Using a Switch to Get and Ready!

With our variables initialized and defined, nosotros'll now use a switch statement against the type argument in order to determine what exactly we'll exist doing.

  • Example "Edit":

    If the case is edit, we'll be making this element editable. As a result, nosotros'll need to practise three things:

    • The text value of the element

      First off, nosotros'll define a new variable, val, as this elements text value.

    • Storing the text for later

      Using jQuery'due south $.data method, nosotros'll attach val to this chemical element! The $.information method is a fantastic fashion to associate data with an element. For setting data, we'll need to specify 3 arguments, element, key and value.

      For more than information on jQuery's $.data method have a look at the jQuery API

    • Defining the html string

      Lastly, we'll define the html var as a cord representation of an input element. This cord will be used to both create and inject this chemical element with just 1 phone call to jQuery's html method.

      We'll set the name aspect of this input past concatenating the appropriate value from the fieldNames array into the html string. This is where we'll use the alphabetize statement every bit it represents the index of the current element in the loop. And so, if were working with _editable[0] the advisable field proper noun should be stored in fieldNames[0]!

      In like fashion, we'll the concatenate val into the string as the input's value aspect.

  • Instance "Restore":

    If type evaluates to restore, we'll but need to retrieve the text for this element.

    • Retrieving $.data

      Retrieving $.data is but as simple as setting information technology. We only need to call the $.data method with two arguments, element and key.

  • Example "Update":

    If the type argument evaluates to update nosotros'll define our html variable as the updated value from the value attribute of this element's input.

    Then, using jQuery's $.information method over again, we'll update the value we attached to this element and so that it reflects the new value!

    • Getting the Inputs Value

      Using jQuery'south attr method. nosotros'll define the html var as the value attribute of the input.

  • Default:

    • Setting the Default:

      We'll have the switch default to return in the case that the type argument somehow doesn't evaluate to one of the appropriate strings.

The entire switch statement

With all of our cases defined, here's a look at the entire switch argument


Setting the HTML

Using jQuery'due south html method, we'll now fix the string nosotros've defined equally the html for this element.


Returning Something Useful

With our $.each loop finished, nosotros're now ready to finish this method. We'll practice and then past returning this and so that this method is chainable.


_transformElements in its entirety

That's it, hither's a look at the completed _transformElements method:



Deleting elements from the DOM with _removeElements


The _removeElements method will be chosen only when a user has successfully deleted data with an AJAX request. In other words, this method will be a callback to a successful AJAX deletion.


Arguments

This method takes but one argument, i, which will be used to select the appropriate selector for the _elementParent we're deleting.


Selecting the Content

First, we'll specify which _elementParent we're removing by using i in square bracket / associative array notation. This will give united states the chemical element with an index of i rather than the jQuery selector. Then, we'll make a new jQuery pick from this expression.

We could but every bit hands use jQuery'southward get or eq methods here without making a new jQuery selection. However, in keeping in line with the coding convention we've been using, allow'south just practice the following:

For more information on jQuery'southward get method, bank check the jQuery API

Documentation for jQuery's eq method can also be found in the jQuery API


Removing the Content

Using jQuery's remove method, we'll delete these elements from the DOM!

Documentation for jQuery's remove method can exist institute in the jQuery API


Returning this

Lastly, nosotros'll return this then as not to intermission the concatenation.


_encode: Preparing information for submission!


The _encode method is called just before an AJAX request. Using jQuery's serialize and $.param methods, _encode serializes key / value pairs and returns a url encoded cord.


Arguments

This method takes 1 argument, inputs, which represents a jQuery drove of the elements nosotros desire to serialize.


Serializing Inputs, the Easy Way!

Using jQuery'south is method, which returns a boolean, nosotros'll cheque the inputs argument against an "input" selector. If nosotros are dealing with inputs, is will render truthful and equally such, nosotros'll then phone call jQuery'south serialize method on this collection. serialize takes a grade or a drove of inputs and returns a url encoded string of key / value pairs.

For more than information on jQuery's is method, cheque the jQuery API

documentation for jQuery's serialize method can as well be establish in the jQuery API


Serializing Everything Else!

If the inputs drove is not comprised of input elements, we'll build an object literal comprised of primal value pairs representing, sort of, pseudo proper noun and value attributes.

Once we've created this object, we tin pass it to jQuery's $.param every bit an argument. $.param will serialize an array or object and return the url encoded string not unlike the jQuery serialize method.

  • Initializing an Empty Object

    Permit's initialize the variable information an empty object. Nosotros'll populate this object in a moment equally we iterate through our inputs.

  • Making this.options.fieldNames available

    Next, we'll define the variable fieldNames every bit a reference to this.options.fieldNames. By doing this, nosotros're making this.options.fieldNames available to this method's inner function, $.each. fieldNames also serves as a sort of shorthand manner to admission the options.fieldNames array.

  • Looping though inputs

    Using jQuery'south $.each method, we'll being iterating though inputs. Once again, we're passing an empty argument, alphabetize, to inputs. Equally a upshot, the index of the electric current element in the loop volition be assigned to alphabetize. Next up, the logic of our loop!

    • Caching this

      First, let's cache the jQuery selector for this, the current element in our loop.

    • Defining the cardinal

      The variable cardinal will represent the name attribute for this element. The value of key is stored in the fieldNames array and it's index within that array is equal to the index of the current element in our loop. Thus, fieldNames[alphabetize]should contain the appropriate field proper name for inputs[alphabetize].

    • Fetching the value

      Lastly, we ascertain the variable val as a sort of pseudo value attribute. We'll use jQuery'south text method to go the text of the electric current element in the loop.

    • Building the data object

      With our key / value pairs defined, we'll begin populating the object using square bracket / associative array note. We'll set the key for each item as central and the value equally val. The do good of using this blazon of notation, in this particular context, is that we tin can gear up the key with a variable. In literal notation, the variable fundamental would be interpreted as the string "key".

  • Returning the Encoded Data

    Now that our iteration is complete and the data object is populated, nosotros'll call jQuery's $.param method with information as its statement. $.param will render a url encoded string representation of the object or array passed to information technology.

    For more information on the jQuery $.param method cheque the jQuery API.


The full _serialize method

Here's a look at the complete _serialize method:

huynhoveass.blogspot.com

Source: https://code.tutsplus.com/tutorials/create-a-dynamic-content-editing-system-with-jquery-ui--pre-13149

0 Response to "How to Read Api Documentation for Jquery Ui"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel