Back to all updates

over 7 years ago

Reducing Code Repetition in SciVerse Apps

Sharing code between views
In many cases, a SciVerse application may need to use the same code in several different views.  Rather than repeat the code in each view, a Content section can be created to contain the shared code.  This is possible because Content sections can be repeated and each Content section can be associated with many views.  And as long as each content section is type="html" and doesn't have an href attribute, Content sections will have their contents concatenated.

Consider the following example where both the "profile" and "canvas" views use a getContextInfo() Javascript function to retrieve the context information.

blog post photo
Sharing Javascript 
Instead of repeating the getContextInfo() anddisplayContextInfo() functions in each Content section, a new, "shared" Content section can be created to contain this code.  For example, 

blog post photo
Sharing HTML and CSS Styles
It's possible to share more than just Javascript.  Anything that can be placed in a Content section can be shared among views.  This includes CSS styles and HTML.  So, in our example above, the HTML that displays the "Get Context Info" link as well as the "contextInfo" div section can be shared.  For example,

blog post photo
You can see in this example that the "Welcome to..." HTML that is specific to each view has been separated in a different Contentsection than the HTML which displays the "Get Context Info" link.  The example also shows how the Content sections are concatenated together in the order that they appear in the XML specification.  

We can take this a step further by completely separating the common parts of the "Welcome to..." HTML from the parts that are specific to each view.  This is demonstrated in the following example.  In addition, we'll create a shared CSS style for pgTitle.  

blog post photo
For more information on sharing content between views, see the OpenSocial Views Developer's Guide v0.9 (see the Redundant content sections/views section).

The source code for the above examples can be found here.