Search
Categories
Tags
Latest Comments

Entries in namespace (2)

Sunday
Mar142010

Writing Client-Side Javascript for Re-Use, Part II

This is the second post in a series on reuseable javascript objects. If you have not read it yet, start at the first post here.

Now, let's continue on by creating a new, blank database somewhere on your Domino webserver to serve as your new re-usable javascript code repository. A simple URL denoting reusable javascript objects is probably best. For example, at ZO, I've created a database titled "ZetaOne Javascript Repository" in the root of the data directory called zojs.nsf.  Give anonymous reader access to the database so it can be referenced from any application. In that new database, lets create a new client side javascript library. with the name "com/ZetaOne/widget/listControl.js".  The name is important.  The script library name needs to match what we are going to define our new class as. I'll explain why later.

Lets get started by entering a few basic lines to define the actual class:


dojo.provide("com.ZetaOne.widget.listControl");

(function(){
        dojo.declare("com.ZetaOne.widget.listControl", dijit._Widget, {
            create: function(params, srcNodeRef) {

            },
            destroy: function() {

            }
        })
})();

This is the very basic definition if our new class. the first line "dojo.provide" plugs our new class into the dojo runtime, so dojo knows it has been loaded. This is important, as different objects can reference the same class multiple times, but it will only be loaded one time to save download time and bandwidth, and to prevent existing data from getting over-written by one module reloading an existing module.

The next line "(function(){" creates whats known as an anonymous function that allows us to define our new "class". Which is where the third line "dojo.declare" comes in. That block of code creates a new "class" called com.ZetaOne.widget.listControl that inherits from dijit._Widget (dijit._Widget is the base class in dojo from which most all UI controls are derived. We won't get into why we're inheriting from this class in this post, just know that we have basically now extended dijit._Widget).  Our new class also has two new members "create" and "destroy" which are just like standard constructors and destructors in languages that implement a real class.

We can add additional member objects, variables and functions by declaring them just like the create and destroy functions are defined.  For reference, here is the entire implementation of the com.ZetaOne.widget.listControl object as it has been implemented as a class object. We won't get into the nitty gritty of what is going on with this class, but it's here as an example. In a later post, we'll get deeper into this actual object to describe the mechanations at work.

dojo.provide("com.ZetaOne.widget.listControl");

(function(){
        // PUBLIC MEMBERS
        dojo.declare("com.ZetaOne.widget.listControl", dijit._Widget, {
            create: function(params, srcNodeRef) {
                    if (typeof srcNodeRef == 'undefined') {
                        console.error('com.ZetaOne.widget.listControl requires a DOM node!');
                        return false;
                    } else
                        this.domNode = srcNodeRef;
        
                    this.id = this.domNode.id;
                    this.inherited(arguments);
                    this.selectMultiple = dojo.attr(this.domNode, 'selectMultiple');                            
                    this.groupClass = dojo.attr(this.domNode, 'groupClass');
                    this.itemClass = dojo.attr(this.domNode, 'itemClass');
                    this.selectedClass = dojo.attr(this.domNode, 'selectedClass');
                    this.lastSelectedClass = dojo.attr(this.domNode, 'lastSelectedClass');                    
                            
                    this.selectMultiple = (this.selectMultiple == null) ? "true" : eval(this.selectMultiple);
                    
                    this.groupClass = (this.groupClass == null) ? 'zoListControlGroup' : this.groupClass;
                    this.itemClass = (this.itemClass == null) ? 'zoListControlItem' : this.itemClass;
                    this.selectedClass = (this.selectedClass == null) ? 'zoListControlSelected' : this.selectedClass;
                    this.lastSelectedClass = (this.lastSelectedClass == null) ? 'zoListControlLastSelected' : this.lastSelectedClass;
                                    
                    this._itemClassQuery = '.' + this.itemClass;
                    this._groupClassQuery = '.' + this.groupClass;
                    this._selectedClassQuery = '.' + this.selectedClass;
                    this._lastSelectedClassQuery = '.' + this.lastSelectedClass;
                
                    if (dojo.isIE)
                        document.onselectstart = function() { return false; }
                    else {            
                        document.onmousedown=this._disableselect;
                        document.onclick=this._reEnable;
                    }
                    
                    // associate onclick events
                    var selectables = dojo.query(this._itemClassQuery);
                    for (i=0;i<selectables.length;i++) {
                        dojo.addClass(selectables[i], this.groupClass);
                        this.connect(selectables[i], 'onclick', this._captureClick);
                    };
                    
                    return;                            
            },
            destroy: function() {
                    dijit.registry.remove(this.id);
                    dojo.forEach(this._connects, this.disconnect);
                    this.inherited(arguments);        
            },
            pop: function() {
                    var nodes = dojo.query(this._groupClassQuery + this._selectedClassQuery);
                    for (i=0;i<nodes.length;i++) {
                        nodes[i].parentNode.removeChild(nodes[i]);
                        this.disconnect(this._connects[nodes[i].id]);
                    }
                    nodes.removeClass(this.selectedClass);
                    nodes.removeClass(this.itemClass);
                    nodes.removeClass(this.groupClass);
                    nodes.removeClass(this.lastSelectedClass);
                    return nodes;                    
            },
            push: function(nodes, select) {
                    nodes.addClass(this.groupClass);
                    nodes.addClass(this.itemClass);
                    if (select) nodes.addClass(this.selectedClass);
                    
                    for (i=0;i<nodes.length;i++) {
                        this.domNode.appendChild(nodes[i]);
                        this.connect(nodes[i], 'onclick', this._captureClick);
                    }
            },
            connect: function(
                    /*Object|null*/ obj,
                    /*String|Function*/ event,
                    /*String|Function*/ method){
                var d = dojo;
                var dc = dojo.connect;
                this._connects[obj.id] = dc(obj, event, this, method);
                return this._connects[obj.id];
            },
            disconnect: function(/*Object*/ handle){
                // summary:
                //        Disconnects handle created by this.connect.
                //        Also removes handle from this widget's list of connects
                // tags:
                //        protected
                var i = dojo.indexOf(this._connects, handle);
                dojo.disconnect(handle);
                this._connects.splice(i, 1);
                return;
            },            
            // PRIVATE MEMBERS    
            _selectItem: function(selection, e) {
                    
                    var selNode = dojo.byId(selection);
                    
                    if (((!e.ctrlKey) && (!e.shiftKey)) || !this.selectMultiple) {
                    
                      dojo.query(this._groupClassQuery + this._itemClassQuery).removeClass(this.selectedClass);
                      dojo.addClass(selNode, this.selectedClass);
                    
                    } else if ((e.ctrlKey) && (!e.shiftKey))
                    
                      if (dojo.hasClass(selNode, this.selectedClass))
                        dojo.removeClass(selNode, this.selectedClass)
                      else
                        dojo.addClass(selNode, this.selectedClass);
                    
                    else if (e.shiftKey) {
                    
                      var idx = dojo.indexOf(selNode.parentNode.childNodes, selNode);
                      var lastIdx = dojo.indexOf(selNode.parentNode.childNodes, dojo.query(this._groupClassQuery +
                              this._groupClassQuery + this._lastSelectedClassQuery)[0])
                    
                      if (idx == lastIdx) {
                          // user just shift clicked the same node again, don't do anything
                          return true;
                      }
                
                      if (!e.ctrlKey) {
                        // clear all previous selections first, re-add lastSelected, then process on
                        dojo.query(this._groupClassQuery + this._selectedClassQuery).removeClass(this.selectedClass);
                        dojo.query(this._groupClassQuery + this._selectedClassQuery).addClass(this.selectedClass);
                        dojo.addClass(selection, this.selectedClass);
                      }
                      
                      if (lastIdx == -1) {  // the last selected was not in the same parent, so we can't shift click, so just reset the focused nodes and select the single node ...
        
                        dojo.query(this._groupClassQuery + this._selectedClassQuery).removeClass(this.selectedClass);      
                        dojo.addClass(selNode, this.selectedClass);
        
                      } else {
        
                          if (idx < lastIdx) {
                            var el = selNode;
                            for ( ; lastIdx >= idx; idx++) {
                              if ((el.nodeType == 1) && (dojo.hasClass(el, this.groupClass)))
                                dojo.addClass(el, this.selectedClass);
                              el = el.nextSibling;
                            }        
                          } else if (idx > lastIdx) {
                            var el = selNode;
                            for ( ; lastIdx <= idx; idx--) {
                              if ((el.nodeType == 1) && (dojo.hasClass(el, this.groupClass)))
                                dojo.addClass(el, this.selectedClass);
                              el = el.previousSibling;
                          }
                        }        
                      }    
                    }
                    
                    dojo.query(this._groupClassQuery + this._lastSelectedClassQuery).removeClass(this.lastSelectedClass);
                    dojo.addClass(selNode, this.lastSelectedClass)
            },    
            _disableselect: function(e) { return false; },
            _reEnable: function() { return true; },
            _captureClick: function() {
                var e = (!arguments[0]) ? window.event : arguments[0];
                var selection = (e.target) ? e.target : e.srcElement;
                this._selectItem(selection.id, e);
        
            }
        })
})();    

Copy and paste that code into your "com/ZetaOne/widget/listControl.js" library, then save and close it.
Now in a different database, let's create an XPage that consumes this object. First create an XPage with the following code, making sure to set dojo ParseOnLoad and dojoTheme to true in the XPage's All Properties:

        <xp:div dojoType="com.ZetaOne.widget.listControl" styleClass="sourceUserList"
            id="userSourceList">
            <xp:this.dojoAttributes>
                <xp:dojoAttribute name="groupClass" value="userGroup" />
                <xp:dojoAttribute name="itemClass" value="userItem" />
                <xp:dojoAttribute name="selectedClass" value="focused" />
            </xp:this.dojoAttributes>
            <xp:repeat value="#{javascript:return new Array('Item 1','Item 2', 'Item 3', 'Item 4');}" var="profileVar" indexVar="profileIndex"
                rows="4">
                <xp:div id="userSelectable" styleClass="userSelectable userItem">
                    <xp:text escape="true" value="#{profileVar}" disableTheme="true" />
                </xp:div>
            </xp:repeat>
        </xp:div>


There are a couple of things to point out in the above code. First, notice the first xp:div tag has a dojoType that matches the class we defined earlier "com.ZetaOne.widget.listControl".  This instructs dojo to create an object out of this HTML element based on that class.  The <xp:dojoAttribute> tags are used to pass parameters to the constructor function of the class. Additionally, if you have been following along in this series so far, you might notice that we are don't have code in the XSP markup to handle the onClick events when the user selects an item. This has been automated in the class, and we'll review in a future post.

To make this a working model, you'll also need to assemble the Cascading Style Sheet from the previous two posts, place it in the database, and include it as a reference on this page.
We now have a complete implementation of the listControl object in an application, BUT we still need to tell the browser to actually load the javascript class that we created in our new javascript repository.

We'll cover that in Part 3.

Sunday
Mar142010

Writing Client-Side Javascript for Re-Use

Many of us "grew up" through the evolution of Lotus Notes and Domino and have been conditioned to not use our tools in the the cleanest, most effective manner. For example, quite often we have scores of LotusScript libraries, chocked full of one-off sub-routines, functions that work together, but have no logical connection in code like a class, and quite frequently these libraries are not well document, coded "ugly" instead of readable, and have lots of "legacy implementations" making it difficult for us to adopt better, if not best practices.

With the advent of XPages, and a new set of tools with which to build our applications, we get a unique opportunity to "get it right" from the beginning. The thoughts of "best practices" and how to implement Server Side and Client Side Javascript libraries for re-use in XPages has been on my mind heavily of late. I've come to the conclusion that we don't have to re-invent the wheel. We already have a powerful model to follow in Dojo.

What does this mean? Well over the next few posts, I'll take a look at a few concepts, and some practical applications around them.

Lets talk first about client-side javascript and namespaces.

If you haven't spent a lot of time learning the intricacies of how Dojo, or any other javascript framework works, such as Ext, jQuery, or the like, and haven't delved into Java, you may not be that familiar  with the concept of namespaces.  While the full bredth and scope of why namespaces are a "best practice" and what they mean overall is beyond this post, let me briefly describe them and point out some obvious reasons why they are a good idea.

If you looked at all into using dojo in XPages, or looked at the XSP object at all, you may have noticed how all the dojo modules are named similar to "dojo.dnd.Source" or "dijit.layout.BorderContainer". Quite simply these are "namespaces" and are meant to uniquely identify a block of code, similar in concept to classes. While javascript does not have classes per se, the flexibility of the language has allowed the creation of constructs that give javascript objects class-like functionality.

From the simplest perspective, these namespaces help us to keep code from one script from stepping on code from another. The flexibility inherent in javascript to .prototype objects, or to create objects without private or protected members easily allows this to happen.

So as a best practice, you should start to define your own namespaces in your code, creating a base of re-usable components that you can use from XPage application to XPage application.

That being said, because domino is SO good at being a distributed platform, it often makes it difficult to effectively share objects between applications. Especially javascript libraraies. Code control can become a nightmare as you develop revisions, and then place them in different nsf stores. Sure you can do overly complex multi-template inheritance to create a psuedo code-revision control "framework", but it is very fragmented at best.

What I've done here at ZetaOne is to create a single script library database for all re-usable client side Javascript libraries. What this allows me to do is "require" any reusable piece of javascript code from this single library. Every logical block of code is then coded into a namespace, designed after the "Dojo" way of defining namespaces and objects. As we continue this series, we'll start to build onto these namespaces to enable greater and greater functionality, and integration into the dojo namespace.

So, lets look specifically at what at namespace is, and how to implement it. Simply put, namespaces are a unique identifier assigned to a block of code. The "Dojo Way" is to start with a base names set (in dojo's namespace, its "dojo", and then from there you add a "." and then the name of the "class" you want to implement. For example, all dojo drag and drop functionality is located under the "dojo.dnd" namespace.

Ok, so what do we use for our own namespace?  Well, the accepted convention is your reverse domain name. For example, all my code is under the "com.ZetaOne" namespace. I then add on from there for each particular class or application I create.  For example, as I build reusable objects that represent backend functions and operations, I create them under the "com.ZetaOne.api" namespace.  Objects that are UI controls, for users to interact with are under the "com.ZetaOne.widget" namespace. In single database applications, each application has it's own namespace under "com.ZetaOne.app", and larger, multi-applcation, multi-database systems usually get their own namespace directly under "com.ZetaOne", such as "com.ZetaOne.AppName".

Ok, so there is the basics on what we call our namespace, how do we actually define it? Well, in my next post, i'll start by taking the HTML selection function I wrote about in my last few posts, and convert it to a re-usable, namespaced object.

Stay tuned and Happy Coding!