1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Building OpenSocial Apps- P6 doc

50 220 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 50
Dung lượng 654,44 KB

Nội dung

ptg 224 Chapter 10 OSML, Gadgets, and the Data Pipeline Table 10.6 os:ActivitiesRequest Attributes Attribute Description Key Required. A string value used to identify this data within the DataContext. The key value must be unique within the app across all data tags. userId Required. A comma-delimited list of IDs to use in conjunction with the groupId attribute. Valid values are @viewer @owner a specific user ID groupId Optional. The group of users to get, relative to the value defined in the userId attribute. If this is not speci- fied, it defaults to @self, which means the person object(s) corresponding to the value of the userId attribute. Valid values are @self @friends The value @self means the records specified in the userId attribute. The value @friends means friends of the user(s) specified in the userId attribute. Fields Optional. A comma-delimited list of OpenSocial activity fields to return with each record. startIndex Optional. In a paged list of records, this specifies the starting index for results. Count Optional. An integer value specifying the maximum number of records to return. Table 10.7 os:DataRequest Attributes Attribute Description Key Required. A string value used to identify this data within the DataContext. The key value must be unique within the app across all data tags. method The REST endpoint method used for this request. Currently, only GET requests are allowed. Valid requests are people.get (equivalent to os:PeopleRequest) activities.get (equivalent to os:ActivitiesRequest) More endpoints are being added all the time, so check the MySpace developer site for the latest information. From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg JavaScript Blocks in OSML Apps Warning Gadget XML and OSML must be a well-formed XML document. To prevent surprise parsing errors stemming from your JavaScript code, always make use of CDATA tags in your JavaScript blocks. All apps that make use of OSML or Data Pipelining must be in gadget XML format and consist of well-formed XHTML content only. If your Content blocks wrap their innards in CDATA tags as is suggested in some of the older Gadget XML documentation, none of the OSML or Data Pipeline tags will be evaluated. As a result, your app code must consist of well-formed XHTML content only.Any JavaScript code containing a “less-than” or “greater-than” test will violate this requirement. Here is an example: if(i > 0){ The solution is to wrap all your JavaScript blocks in a CDATA section: <script type="text/javascript"> //<![CDATA[ function foo(){ // Do something } //]]> </script> Wrapping the client script block contents with CDATA sections instructs the OSML parser to ignore things that might otherwise look like tags inside. Even though tags are not evaluated, expression language statements will be.Therefore, the following statement will still work: var greeting = "Welcome to my app, ${vwr.displayName}"; OpenSocial Markup Language The OpenSocial Markup Language, or OSML, is a tag-based markup language for adding and defining reusable user interface components, easily displaying content from an external server, and managing simple control flow.When OSML is coupled with Data Pipelining, it becomes a formidable new way of writing apps. In this section we introduce some of the basic tags available in the initial version of OSML. OpenSocial Markup Language 225 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg Basic Display Tags There are a limited number of convenience tags defined within OSML.These tags allow simple and common UI elements to be easily rendered.The tag set is currently small, but look for more complex UI elements to be added over time.Table 10.8 identifies the cur- rent built-in OSML markup tags. Remote Content Display Tags HTML partial fragment rendering has become a common Ajax technique. OSML provides a simple tag for displaying inline content from remote servers via a GET request. MySpace also provides a more general-purpose display extension tag.Table 10.9 identifies these two tags. Control Flow Tags There are two basic mechanisms provided for display control flow: os:If and os:Repeat. Additionally, MySpace provides an extension to os:If to give it an “else” syntax as well.Table 10.10 identifies the control flow tags available in OSML Putting It Together: OSML Tic-Tac-Toe Our previous “Hello World” gadget app gave a light introduction to using Data Pipeline tags along with the general gadget structure. Now we’re going to take what we’ve seen so far and apply it to our existing Tic-Tac-Toe app to see what happens. 226 Chapter 10 OSML, Gadgets, and the Data Pipeline Table 10.8 OSML Markup Tags Tag Purpose os:Name The specified person’s display name, hyperlinked to the person’s Profile os:Badge The formatted Profile thumbnail image and name, hyperlinked to the person’s Profile os:PeopleSelector Displays a FriendPicker, scoped to the identified group Table 10.9 Remote Content Display Tags Tag Purpose os:Get Fetches the markup from an arbitrary URL via an HTTP GET request and displays it inline at the tag location myspace:RenderRequest Fetches the markup using any HTTP method supported by gadgets.io.makeRequest. Contents may be displayed inline or in a specified element. From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg Setting Up the Gadget Our first step is to move the existing code as is into the gadget XML format. For this step we’ll make use of our desktop code editor to paste all three of the existing app surfaces into an empty gadget XML file.The OpenSocial Sandbox tool will be our best friend for validating our work in this initial stage. Creating the Initial Gadget File from Existing Code Here we will construct the initial app gadget XML source file from the code blocks we have already developed using the app Surface Editor. At the end of these steps we will have our same app in the gadget XML format. 1. Navigate to the Sandbox by clicking Tools → OSTool/Harness from the developer site and clicking the Try the Beta OpenSocial Sandbox Editor link to open the Sandbox Editor (shown in Figure 10.1). 2. Copy the contents of the Blank Sample Gadget and paste it into a new code file in your code editor (Aptana for us). 3. Change the value of the “title” attribute of the <ModulePrefs> element from “Hello World” to “OpenSocial Tic-Tac-Toe.” 4. Save your file as OpenSocialTTTGadget.xml. 5. Open the source for the Home Tic-Tac-Toe surface in your code editor. 6. Copy the entire contents of the Profile code file and paste it into your new gadget in the Profile view template script.The surrounding code will look like this: <Content type="html" view="home"> <script type="text/os-template"> // PASTE THE CODE FROM Tic-Tac-Toe HOME SURFACE HERE </script> </Content> 7. Copy the contents of your new gadget file and paste them into the Sandbox Editor. Putting It Together: OSML Tic-Tac-Toe 227 Table 10.10 OSML Control Flow Tags Tag Purpose os:If A conditional block that is shown if the expression statement evaluates to true osx:Else Inverse conditional support for os:If. This is a MySpace extension to the OSML specification. The osx:Else tag must appear immediately adjacent to an os:If tag. os:Repeat Iterates over an array of data items and displays the contents of the repeat tag, evaluated for each data item From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 8. Select the Home view from the Views drop-down and click Render.You will see an error similar to the following: An error occurred while parsing EntityName. Line 210, position 43. // First check if there was an error back from the proxy if(!response || (response.errors && response.errors.length > 0) || response.errorCode){ retryRequest(); } We need to fix these parsing errors before we can get any further. Fix Parsing Errors The error we encountered was caused by a greater-than comparison occurring within a JavaScript block.To get around this, we’ll wrap all client JavaScript script tag contents in CDATA sections: 1. Go back to the gadget code in your source editor. 2. Search for all the <script> tags that do not have a type attribute of text/os-template or text/os-data. 228 Chapter 10 OSML, Gadgets, and the Data Pipeline Figure 10.1 OpenSocial Sandbox Editor. From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 3. Add an opening CDATA tag immediately after the script tag and a closing CDATA tag immediately before the closing </script> tag.These tags should be preceded by JavaScript inline comment characters. Here is an example of what the updated script block will look like: <script type="text/javascript"> //<![CDATA[ . . . //JavaScript code excluded for brevity //]]> </script> 4. Save the results and re-render using the Sandbox Editor as before.When it is working correctly, you should see the Home view, rendered as in the live app (as shown in Figure 10.2). Adding Other Surfaces The other two surfaces must also be added to the gadget file. Paste the Profile and Canvas code into the templates in the appropriate Content blocks of your gadget file. Make sure you add CDATA sections to all JavaScript blocks until the Sandbox Editor can render all three surfaces without any parsing errors. There is one more issue that will surface when reconciling the existing JavaScript app with the gadget/OSML format. Activity templates make use of an expression marker in their templates that’s similar to one found in the Data Pipelining expression language. Both use the format ${SOME_VAR} to define an expression.The OSML renderer, finding the embedded activity templates, will attempt to resolve the contained tokens as Putting It Together: OSML Tic-Tac-Toe 229 Figure 10.2 Sandbox rendering of Home. From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg expressions and hiccup.The resolution is to build up the activity template strings in a way that does not look like an expression to the server-side OSML processor. Search the gadget code for "${" and make the following changes: // Version using the default template function rsmNotification(recipient, game_id){ // Set up all the data we'll need var body = "$" body += "{sender} has finished their move "; body += "in $" body += "{app}, it's your turn!"; This splits the activity template expression up so the server doesn’t recognize it, but the template still looks the same to the client code. Reusing Common Content We have now created a single-source-file behemoth for our app, weighing in at almost 2500 lines of code. It’s nice to have a single source file for storage and tracking purposes, but it can be a bit ungainly to manage from a code maintenance standpoint.The Aptana IDE does a nice job of allowing you to expand and collapse nodes for easier visibility, but that’s no substitute for cleaning up our code.We need to DRY things out a bit. 230 Chapter 10 OSML, Gadgets, and the Data Pipeline The DRY Principle The acronym DRY stands for Don’t Repeat Yourself. It’s a clever catchphrase to remind developers to reuse code as much as possible. One of the failings of using the Surface Editor for writing apps is that you will find yourself repeating the same code over and over again. With an OSML gadget an app can reuse parts of the code through the use of shared Content blocks. If we look at our code, we’ll see a lot of repeated lines across the three surfaces. In fact, putting the original Home and Profile source files in a diff tool (we used WinMerge), we find that there are only five differences, consisting of an additional style on Profile, some slightly different text on the button between the two, and a trailing div on Profile.Through the use of shared Content blocks, we can almost immediately remove 98% of the code associated with one of these surfaces. Merging Home and Profile with Shared Content Blocks Gadgets and, by extension, OSML define their different surfaces with <Content> blocks. The view attribute of a Content block identifies the surface for which the enclosed content is valid. During rendering of the OSML gadget, any and all Content blocks that From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg have a view value matching the current surface are rendered in the order in which they are encountered in the gadget XML file. If a particular block of content is valid on more than one surface, it may be identified as such by using a comma-delimited list of surface names for which it is to be rendered.This is in contrast to the app Surface Editor, which allows one and only one discrete view per surface. Our diff of the Home and Profile sources showed that there are relatively few differ- ences between the two. Since Profile seems to be a superset of the Home view, with some small textual changes, we’ll use that as the basis for both surfaces. Creating Shared Style Content Blocks One of the powers of the gadget XML format is the ability to stream shared code blocks across multiple surface views. In this section we use the notion of specifying multiple valid view values in a single Content block in order to share common markup, styles, and JavaScript between the Home and Profile surfaces. 1. Edit your app’s gadget XML file to completely delete the home Content block. 2. Change the profile Content block to also include the Home view, like this: <Content type="html" view="profile, home"> 3. Save your changes and view them using the Sandbox tool.The Home and Profile surfaces should now match. 4. Add three new Content blocks with template script tags above the existing com- bined Home and Profile block.The first block will be used to hold the common styles.The second two will hold view-specific styles.The code should look like this: <Content type="html" view="profile, home"> <script type="text/os-template"> </script> </Content> <Content type="html" view="profile"> <script type="text/os-template"> </script> </Content> <Content type="html" view="home"> <script type="text/os-template"> </script> </Content> 5. Add the complete <style> block to the first shared Content block. Putting It Together: OSML Tic-Tac-Toe 231 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 6. Create new style elements in both the subsequent blocks and cut and paste the subtitle-style class definition out of the shared style area and into each private style block. Modify the Home surface’s version to be display:none; the two private style blocks should appear as shown here: <Content type="html" view="profile"> <script type="text/os-template"> <style> .subtitle { margin:5px 0; } </style> </script> </Content> <Content type="html" view="home"> <script type="text/os-template"> <style> .subtitle { display:none; } </style> </script> </Content> 7. Save and view the results.The Profile surface should still show the subtitle, but the Home surface should be free of the subtitle. There is still one visible issue.The button text is incorrect on the Home view.We’ll fix that by adding some client-side JavaScript to modify the button’s text for the Home view. Customizing the Button Text Between Views There are supposed to be some minor differences between the Home and Profile views of our app. In this section we add some subtle changes in a Content block specific to the Home view that fixes the button to show appropriate text whether on the Home view or the Profile view. 1. Find the button element in the shared Profile/Home content template. It should look like this: <button onclick="rNT(gadgets.views.ViewType.CANVAS);"> Click here to challenge me!</button> 2. Modify the element to add an attribute of id="playButton" to the button element. 232 Chapter 10 OSML, Gadgets, and the Data Pipeline From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 3. Add a new Content block after the shared Profile/Home Content block that is specific to the Home view. Include the template script tags and client-side JavaScript script tags. <Content type="html" view="home"> <script type="text/os-template"> <script type="text/javascript"> //<![CDATA[ //]]> </script> </script> </Content> 4. Add an inline JavaScript statement to change the text of the button by manipulating the DOM: document.getElementById("playButton").innerHTML = "Click here to play now!"; 5. Save and view the results.The Home view should now show the proper button text. Here is an abbreviated code listing of the updated Home/Profile content blocks: <Content type="html" view="profile, home"> <script type="text/os-template"> <style> body { background-color:#1E4C9F; color:#fff; margin:0; padding:0; } img { border:0; } </style> </script> </Content> <Content type="html" view="profile"> <script type="text/os-template"> Putting It Together: OSML Tic-Tac-Toe 233 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... object: _initTabs:function(){ this._tabs[0] = new TTT.Tab(document.getElementById("tab0"), "canvas.play", playClicked); this._tabs[1] = new TTT.Tab(document.getElementById("tab1"), "canvas.invite", inviteClicked); this._tabs[2] = new TTT.Tab(document.getElementById("tab2"), "canvas.challenge", challengeClicked); this._tabs[3] = new TTT.Tab(document.getElementById("tab3"), "canvas.setBackground", setBackgroundClicked);... http://code.google.com/p/opensocialtictactoe/source/browse/#svn/ trunk/chapter11 Using Client-Side Templates Custom templates are also available for use in client-side code All your custom templates are available for use on the client side via the new opensocial. template namespace This allows your app to create and render new template instances on the client.The call sequence looks something like this: var templateInst = opensocial. template.getTemplate("my:CustomTag");... gets a template instance using the opensocial. template.getTemplate function and then calls renderInto to render the template into our opponentinfo div.The function looks like this: function updateOpponentTemplate(player){ var elem = document.getElementById("opponentinfo"); if(!player){ elem.innerHTML = ""; return; } //Get a new instance of the template var tplate = opensocial. template.getTemplate("my:PlayerInfo");... addition to the OpenSocial spec and supported starting only in version 0.9 At the time of this writing, OSML and Data Pipelining are not even fully released and aren’t recognized by previous versions, whereas the OpenSocial JavaScript API has more than a year under its belt and is fairly stable.We encourage you to push the limits with OSML, though, and give your feedback both to MySpace and to the OpenSocial. .. rendering of the results using the my:YImageSearchResults template we just created function tttImagesLoaded(key){ var tab = document.getElementById("tab5"); tab.style.background="red"; var tplate = opensocial. template.getTemplate( "my:YImageSearchResults"); var dataContext = opensocial. data.getDataContext(); var d = dataContext.getDataSet(key[0]); var tdata = {} tdata["searchResults"] = d.ResultSet;... (vwr.DateOfBirth); 7 Assign the contents of your string to the innerHTML of the element internal to the player bio div and assign the entire bio contents to the lightbox: var bioElem = document.getElementById("playerBioWrapper"); var bioContents = document.getElementById("bio_contents"); bioContents.innerHTML = str; //Add to lightbox TTT.LightBox.setContent(bioElem.innerHTML); //Now show TTT.LightBox.show(); 8 Update... chapter we’ll do a little more of that, plus introduce some new features that open even more doors to our app Remember, though, OSML is a very late addition to the OpenSocial spec, and it is supported beginning only with version 0.9 of the OpenSocial specification; previous versions do not recognize OSML Inline Tag Templates Inline tag templates are reusable components that are declared directly inside... type="text/os-template"> Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark From the Library of Lee Bogdanoff Putting It Together: OSML Tic-Tac-Toe 235 // Working with Data Having shared display code among the surfaces is great Having shared... class="profile_image" src="${viewer.thumbnailUrl}" /> ${viewer.DisplayName} 4 Search for the call to printPerson in the JavaScript It is in the getDataCallback function Comment out this call: // printPerson(document.getElementById("myinfo")); Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark From the Library of Lee Bogdanoff 236 Chapter 10 OSML, Gadgets, and the Data Pipeline 5 Save... watermark From the Library of Lee Bogdanoff Working with Subviews 245 Working with Subviews Subviews are a new concept introduced with OSML So, yes, that means they work only starting with version 0.9 of the OpenSocial spec If you’re writing or editing an app for a lower version, you won’t be able to use subviews In addition to the main surface views (Home, Profile, and Canvas), subviews allow for multiple . greeting = "Welcome to my app, ${vwr.displayName}"; OpenSocial Markup Language The OpenSocial Markup Language, or OSML, is a tag-based markup language. the <ModulePrefs> element from “Hello World” to OpenSocial Tic-Tac-Toe.” 4. Save your file as OpenSocialTTTGadget.xml. 5. Open the source for the Home

Ngày đăng: 21/01/2014, 12:20

w