SlideShare uma empresa Scribd logo
1 de 14
Customizing the List control – Sencha Touch
A post from my blog http://jbkflex.wordpress.com on how to customize the look and feel of the default Sencha List
control.


In this tutorial I am going to discuss and show you how to customize the look and feel of the default Sencha List
control. As you might know the normal list control that Sencha provides has a basic structure which looks like the
image on the left below. You can see that it has got individual list items which are laid down vertically and can be
scrolled down to see more items. List uses an Ext.XTemplate as its internal templating mechanism which defines the
look and feel. The data for the List comes from a Ext.data.Store which is bound to it. Whenever there is a change in
data in the Store the change is automatically reflected in the List since it is bounded. I have discussed about how to
create basic List in my previous tutorials. Now let’s modify the look of the List control. We will make a List that looks
like the image on the right. You can see in the new list, it is complete customization of each items. So, now we have
more of a <div> block with custom styles and images. Let’s see how this can be done.




Item Templates / XTemplates
If you have worked with Flex you might have heard of something called ItemRenderer. Ok, let me tell a little about
them if you have no idea. So, ItemRenderer’s are like custom templates using which you can customize the look of
your List items, or it can be any Data control for eg. a DataGrid as well. Here is a good tutorial on ItemRenderers. So,
we are going to do similar things in our Sencha List control.
Ok now, let’s talk a little about item templates before we move to the actual work in hand. Item templates are created
by using the Ext.XTemplate class and it will define the look and feel along with what fields you will be displaying in
each of your list item. This is how to create basic XTemplate




  var tpl = new Ext.XTemplate(

                                       '<p>Kids: ',

                                       '<tpl for=".">',                // process the data.kids node

                                            '<p>{name}</p>',           //display the name

                                       '</tpl></p>'

                                 );


As you can see in the simple example we have created a basic XTemplate. The tpl tag and the for operator are used
to process the provided data object. It is mainly meant for looping the data objects. Remember that your data is
provided by the Store and this can be a JSON data or an XML which has a hierarchical structure something like this

                       var data = {         //JSON data object

                                       name: 'Tommy Maintz',

                                       title: 'Lead Developer',

                                       company: 'Ext JS, Inc',

                                       email: 'tommy@extjs.com',

                                       address: '5 Cups Drive',

                                       city: 'Palo Alto',

                                       state: 'CA',

                                       zip: '44102',

                                       drinks: ['Coffee', 'Soda', 'Water'],

                                       kids: [{

                                                  name: 'Joshua',

                                                  age:3
},{

                                                  name: 'Matthew',

                                                  age:2

                                            },{

                                                  name: 'Solomon',

                                                  age:0

                                       }]

                                 };


As you can see the property kids is an array of objects (with properties name and age). So to loop around each kid
inside the data object we can write something like this in our XTemplate

                                var tpl = new Ext.XTemplate(

                                       '<p>Name: {name}</p>',

                                       '<p>Title: {title}</p>',

                                       '<p>Company: {company}</p>',

                                       '<p>Kids: ',

                                       '<tpl for="kids">',              // interrogate the kids property
within the data

                                            '<p>{name}</p>',

                                       '</tpl></p>'

                                 );


You can see the value assigned to the for operator which is kids, so it will loop through each kid object and print the
name. Also you can see the {name} inside the tags, it is kind of a placeholder or rather a replacement of the object
property. This {name} field defined here actually comes from the model that the store has declared in it. Example
shown below

                                 Ext.regModel('kidModel', {

                                       fields: ['name'] //fields are declared here

                                 });
var kidStore = new Ext.data.Store({

                                           model: 'kidModel',

                                           data: dataObj //that we have defined above

                                    });


Ext.data.Storescan store inline data so we have assigned the value of dataObj that we have created earlier in our
tutorial to the data property inside our store. You can learn more on Ext.data.Stores, Models and XTemplates from
the Sencha Touch API docs. Also I will be posting some more tutorials on these soon. Now to put all these together in
a List, it will look something like this

                                    var myList = new Ext.List({

                                                    id:'myList',

                                                    layout:'fit',

                                                    store:kidStore,

                                                    itemTpl: tpl,

                                                     emptyText:'Sorry, no data!'




                                    });


Ok, we have seen some basic concepts and I will not deviate further away from our real topic on hand that is to
customize the List control.
Customization
To customize the List control, we will have to make changes mainly in our XTemplate where we will create new
HTML elements such as <div> for example, and wrap our data fields inside them and then style our <div>’s that we
have created using basic CSS. So here we go, this will be the data that we will show in our list

                                    var productData = [

                                           {"name": "iPod",       "price": "$300", "image_url":
"images/ipod.png", "in_stock": "yes"},

                                           {"name": "Toaster", "price": "$200", "image_url":
"images/toaster.png", "in_stock": "yes"},
{"name": "Clock", "price": "$120", "image_url":
"images/clock.png", "in_stock": "no"},

                                  ];


Lets define our model with all the fields we need

Ext.regModel('productModel', {fields: ['name','price','image_url','in_stock']});


Now lets create our store that will hold the data

                                  var productStore = new Ext.data.Store({

                                              model: 'productModel',

                                              data: productData

                                  });


Now, most important of all of them, lets create our XTemplate. Before writing code the image below shows the basic
layout structure of the block that we will design for each List item.




As you can see above we have a main <div> block which contains two <div> blocks inside it, the title <div> block and
the body <div> block that will hold the product image and other details. Here is the XTemplate for our custom block

                                 var productTemplate = new Ext.XTemplate(

                                              '<tpl for=".">',

                                                          '<div class="productBox">',

                                                                '<div class="productTitle">',

                                                                        '{name}',

                                                                        '<img class="nextIcon"
src="images/next.png"/>',

                                                                '</div>',

                                                                '<div class="productBody">',

                                                                        '<img class="productImage"
src="{image_url}"/>',
'<ol>',

                                                                            '<li>Price: {price}</li>',

                                                                            '<li>In Stock: {in_stock}</li>',

                                                                      '</ol>',

                                                                '</div>',

                                                           '</div>',

                                              '</tpl>'

                                  );


There are three items in the data so <tpl for=”.”> will loop three times each for one data object. And then it will put
the values of the corresponding fields in the placeholders. As you can see in the code block we have a div box
ofclassname = ‘productBox’. It holds two <div> blocks inside it, one for the title (class = ‘productTitle’) and the
other for the body (class=’productBody’). The styles for them are all defined in the CSS which I will show later. You
can also see in the code block the images that have been put together. Overall the code block is pretty simple and
self-explanatory. Now lets bind the store, template to our list. This is how to do it

                                 var productList = new Ext.List({

                                         styleHtmlContent:true,

                                         store: productStore,

                                         itemTpl: productTemplate,

                                         layout:'fit',

                                         height:"100%",

                                         emptyText:'Oops! No data'

                                  });


And then we can put our List in a Panel for it to display. Lets look at the full code and then I can explain more

<!DOCTYPE html>

<html>

<head>

     <title>Custom List</title>
<link href="css/sencha-touch.css" rel="Stylesheet" />

   <script type="text/javascript" src="js/sencha-touch.js"></script>

   <script type="text/javascript">

       Ext.setup({

                     tabletStartupScreen: 'tablet_startup.png',

                     phoneStartupScreen: 'phone_startup.png',

                     icon: 'images/homeblue.png',

                     glossOnIcon: false,

                     onReady: function(){




                         var productData = [

                              {"name": "iPod",      "price": "$300", "image_url":
"images/ipod.png", "in_stock": "yes"},

                              {"name": "Toaster", "price": "$200", "image_url":
"images/toaster.png", "in_stock": "yes"},

                              {"name": "Clock", "price": "$120", "image_url":
"images/clock.png", "in_stock": "no"},

                         ];




                         Ext.regModel('productModel', {fields:
['name','price','image_url','in_stock']});




                         var productTemplate = new Ext.XTemplate(

                                  '<tpl for=".">',

                                            '<div class="productBox">',

                                                 '<div class="productTitle">',
'{name}',

                                                    '<img class="nextIcon"
src="images/next.png"/>',

                                                '</div>',

                                                '<div class="productBody">',

                                                    '<img class="productImage"
src="{image_url}"/>',

                                                    '<ol>',

                                                        '<li>Price: {price}</li>',

                                                        '<li>In Stock: {in_stock}</li>',

                                                    '</ol>',

                                                '</div>',

                                            '</div>',

                                 '</tpl>'

                        );




                        var productStore = new Ext.data.Store({

                                 model: 'productModel',

                                 data: productData

                        });




                        var productList = new Ext.List({

                              styleHtmlContent:true,

                              styleHtmlCls:'testHtml',

                              overItemCls:'testOver',
selectedItemCls:'testSelect',

                            pressedCls:'testPress',

                            layout:'fit',

                            height:"100%",

                            emptyText:'Oops! No data',

                            store: productStore,

                            itemTpl: productTemplate

                     });




                     //main viewport

                     new Ext.Panel({

                           fullscreen:true,

                           dockedItems:[{xtype:'toolbar', title:'Custom Product
List'}],

                           dock:'top',

                           scroll:'vertical',

                           items:[productList]

                     });

                 }

           });




   </script>

</head>

<body>
</body>

</html>


We have pretty much discussed the things needed to create our custom product list. However, in the productList
control above you can notice some CSS class properties that have been bolded. We have provided some CSS class
names (for eg. testOver) for specific purpose. Here they are

                                        styleHtmlCls:'testHtml',

                                        overItemCls:'testOver',

                                        selectedItemCls:'testSelect',

                                        pressedCls:'testPress',


You might ignore this for your custom List, but I will tell you that these are important. These are predefined CSS class
names for the List control and by setting custom classes you can further control the look of your custom List. These
are the definitions of the properties from the Sencha Touch API docs

styleHtmlCls : String

The class that is added to the content target when you set styleHtmlContent to true.
This means that this CSS class will define the overall look of your list.

overItemCls : String

A CSS class to apply to each list item on mouseover

selectedItemCls : String

A CSS class to apply to each selected item in the list

pressedCls : String

A CSS class to apply to an item in the list while it is being pressed


We will set the CSS styles for all these classes in our CSS block. Lets see our CSS block now

<style>

           .productBox

           {

                border:1px solid #9a9a9a;

           }
.productTitle

{

    border-bottom:1px solid #9a9a9a;

    padding:5px 10px 0px 10px;

    background-color:#ccc;

    font-weight:bold;

    height:30px;

}




.nextIcon

{

    float:right;

}




.productBody

{

    padding:10px;

}




.productBody ol

{

    float:right;

}
.productBody ol li

       {

           list-style:none;

       }




       .productImage

       {

           width:50px;

       }




       .testSelect

       {

           background-color:#efefef;

       }




       .testPress

       {

           /*I want that nothing should happen, so blank*/

       }




       .testHtml

       {

           font-family:'Helvetica Neue', HelveticaNeue, Helvetica-Neue, Helvetica,
'BBAlpha Sans', sans-serif;
font-size:15px;

          }




          .testOver

          {

                background-color:#aaaaaa;

          }

     </style>


Simple CSS code, nothing fancy here. Note the custom CSS classes testOver, testHtml, testPress,
testSelectdefined in the product List. We have put some CSS rules for them. Now, include this CSS block in your
index page and we are ready to go. You should be able to see this at the end
A Custom Product List

Here is the demo application. Open it in your touch phone or test it in http://www.iphonetester.com/ which is an online
iPhone simulator. This is it and we are good to go I guess.

Mais conteúdo relacionado

Mais procurados

4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드영욱 김
 
究極のコントローラを目指す
究極のコントローラを目指す究極のコントローラを目指す
究極のコントローラを目指すYasuo Harada
 
How else can you write the code in PHP?
How else can you write the code in PHP?How else can you write the code in PHP?
How else can you write the code in PHP?Maksym Hopei
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoMohamed Mosaad
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comJD Leonard
 
Entity Query API
Entity Query APIEntity Query API
Entity Query APImarcingy
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentationguestcf600a
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в MagentoMagecom Ukraine
 
MongoD Essentials
MongoD EssentialsMongoD Essentials
MongoD Essentialszahid-mian
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xqueryAmol Pujari
 
[PHP] Zend_Db (Zend Framework)
[PHP] Zend_Db (Zend Framework)[PHP] Zend_Db (Zend Framework)
[PHP] Zend_Db (Zend Framework)Jun Shimizu
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7Zsolt Tasnadi
 

Mais procurados (17)

4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
 
究極のコントローラを目指す
究極のコントローラを目指す究極のコントローラを目指す
究極のコントローラを目指す
 
MongoDB With Style
MongoDB With StyleMongoDB With Style
MongoDB With Style
 
How else can you write the code in PHP?
How else can you write the code in PHP?How else can you write the code in PHP?
How else can you write the code in PHP?
 
Kursus
KursusKursus
Kursus
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
 
Entity Query API
Entity Query APIEntity Query API
Entity Query API
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentation
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
DB2 Native XML
DB2 Native XMLDB2 Native XML
DB2 Native XML
 
MongoD Essentials
MongoD EssentialsMongoD Essentials
MongoD Essentials
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xquery
 
[PHP] Zend_Db (Zend Framework)
[PHP] Zend_Db (Zend Framework)[PHP] Zend_Db (Zend Framework)
[PHP] Zend_Db (Zend Framework)
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
 

Semelhante a Customizing the list control - Sencha Touch mobile web application

JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex DevsAaronius
 
JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptxdyumna2
 
When to NoSQL and when to know SQL
When to NoSQL and when to know SQLWhen to NoSQL and when to know SQL
When to NoSQL and when to know SQLSimon Elliston Ball
 
Spiffy Applications With JavaScript
Spiffy Applications With JavaScriptSpiffy Applications With JavaScript
Spiffy Applications With JavaScriptMark Casias
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETTomas Jansson
 
When Relational Isn't Enough: Neo4j at Squidoo
When Relational Isn't Enough: Neo4j at SquidooWhen Relational Isn't Enough: Neo4j at Squidoo
When Relational Isn't Enough: Neo4j at SquidooGil Hildebrand
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateKiev ALT.NET
 
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010Alex Sharp
 
JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)Raghu nath
 
Disconnected data
Disconnected dataDisconnected data
Disconnected dataaspnet123
 
Sql Portfolio(March 31)
Sql Portfolio(March 31)Sql Portfolio(March 31)
Sql Portfolio(March 31)iceolated
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptLaurence Svekis ✔
 
Ext GWT 3.0 Advanced Templates
Ext GWT 3.0 Advanced TemplatesExt GWT 3.0 Advanced Templates
Ext GWT 3.0 Advanced TemplatesSencha
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 

Semelhante a Customizing the list control - Sencha Touch mobile web application (20)

Intro to sencha touch
Intro to sencha touchIntro to sencha touch
Intro to sencha touch
 
JavaAssignment6
JavaAssignment6JavaAssignment6
JavaAssignment6
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex Devs
 
JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptx
 
Sencha Touch Intro
Sencha Touch IntroSencha Touch Intro
Sencha Touch Intro
 
When to NoSQL and when to know SQL
When to NoSQL and when to know SQLWhen to NoSQL and when to know SQL
When to NoSQL and when to know SQL
 
Spiffy Applications With JavaScript
Spiffy Applications With JavaScriptSpiffy Applications With JavaScript
Spiffy Applications With JavaScript
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
 
displaytag
displaytagdisplaytag
displaytag
 
When Relational Isn't Enough: Neo4j at Squidoo
When Relational Isn't Enough: Neo4j at SquidooWhen Relational Isn't Enough: Neo4j at Squidoo
When Relational Isn't Enough: Neo4j at Squidoo
 
Ch2
Ch2Ch2
Ch2
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
 
JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)JSON(JavaScript Object Notation)
JSON(JavaScript Object Notation)
 
javascript
javascriptjavascript
javascript
 
Disconnected data
Disconnected dataDisconnected data
Disconnected data
 
Sql Portfolio(March 31)
Sql Portfolio(March 31)Sql Portfolio(March 31)
Sql Portfolio(March 31)
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScript
 
Ext GWT 3.0 Advanced Templates
Ext GWT 3.0 Advanced TemplatesExt GWT 3.0 Advanced Templates
Ext GWT 3.0 Advanced Templates
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Último (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

Customizing the list control - Sencha Touch mobile web application

  • 1. Customizing the List control – Sencha Touch A post from my blog http://jbkflex.wordpress.com on how to customize the look and feel of the default Sencha List control. In this tutorial I am going to discuss and show you how to customize the look and feel of the default Sencha List control. As you might know the normal list control that Sencha provides has a basic structure which looks like the image on the left below. You can see that it has got individual list items which are laid down vertically and can be scrolled down to see more items. List uses an Ext.XTemplate as its internal templating mechanism which defines the look and feel. The data for the List comes from a Ext.data.Store which is bound to it. Whenever there is a change in data in the Store the change is automatically reflected in the List since it is bounded. I have discussed about how to create basic List in my previous tutorials. Now let’s modify the look of the List control. We will make a List that looks like the image on the right. You can see in the new list, it is complete customization of each items. So, now we have more of a <div> block with custom styles and images. Let’s see how this can be done. Item Templates / XTemplates If you have worked with Flex you might have heard of something called ItemRenderer. Ok, let me tell a little about them if you have no idea. So, ItemRenderer’s are like custom templates using which you can customize the look of your List items, or it can be any Data control for eg. a DataGrid as well. Here is a good tutorial on ItemRenderers. So, we are going to do similar things in our Sencha List control.
  • 2. Ok now, let’s talk a little about item templates before we move to the actual work in hand. Item templates are created by using the Ext.XTemplate class and it will define the look and feel along with what fields you will be displaying in each of your list item. This is how to create basic XTemplate var tpl = new Ext.XTemplate( '<p>Kids: ', '<tpl for=".">', // process the data.kids node '<p>{name}</p>', //display the name '</tpl></p>' ); As you can see in the simple example we have created a basic XTemplate. The tpl tag and the for operator are used to process the provided data object. It is mainly meant for looping the data objects. Remember that your data is provided by the Store and this can be a JSON data or an XML which has a hierarchical structure something like this var data = { //JSON data object name: 'Tommy Maintz', title: 'Lead Developer', company: 'Ext JS, Inc', email: 'tommy@extjs.com', address: '5 Cups Drive', city: 'Palo Alto', state: 'CA', zip: '44102', drinks: ['Coffee', 'Soda', 'Water'], kids: [{ name: 'Joshua', age:3
  • 3. },{ name: 'Matthew', age:2 },{ name: 'Solomon', age:0 }] }; As you can see the property kids is an array of objects (with properties name and age). So to loop around each kid inside the data object we can write something like this in our XTemplate var tpl = new Ext.XTemplate( '<p>Name: {name}</p>', '<p>Title: {title}</p>', '<p>Company: {company}</p>', '<p>Kids: ', '<tpl for="kids">', // interrogate the kids property within the data '<p>{name}</p>', '</tpl></p>' ); You can see the value assigned to the for operator which is kids, so it will loop through each kid object and print the name. Also you can see the {name} inside the tags, it is kind of a placeholder or rather a replacement of the object property. This {name} field defined here actually comes from the model that the store has declared in it. Example shown below Ext.regModel('kidModel', { fields: ['name'] //fields are declared here });
  • 4. var kidStore = new Ext.data.Store({ model: 'kidModel', data: dataObj //that we have defined above }); Ext.data.Storescan store inline data so we have assigned the value of dataObj that we have created earlier in our tutorial to the data property inside our store. You can learn more on Ext.data.Stores, Models and XTemplates from the Sencha Touch API docs. Also I will be posting some more tutorials on these soon. Now to put all these together in a List, it will look something like this var myList = new Ext.List({ id:'myList', layout:'fit', store:kidStore, itemTpl: tpl, emptyText:'Sorry, no data!' }); Ok, we have seen some basic concepts and I will not deviate further away from our real topic on hand that is to customize the List control. Customization To customize the List control, we will have to make changes mainly in our XTemplate where we will create new HTML elements such as <div> for example, and wrap our data fields inside them and then style our <div>’s that we have created using basic CSS. So here we go, this will be the data that we will show in our list var productData = [ {"name": "iPod", "price": "$300", "image_url": "images/ipod.png", "in_stock": "yes"}, {"name": "Toaster", "price": "$200", "image_url": "images/toaster.png", "in_stock": "yes"},
  • 5. {"name": "Clock", "price": "$120", "image_url": "images/clock.png", "in_stock": "no"}, ]; Lets define our model with all the fields we need Ext.regModel('productModel', {fields: ['name','price','image_url','in_stock']}); Now lets create our store that will hold the data var productStore = new Ext.data.Store({ model: 'productModel', data: productData }); Now, most important of all of them, lets create our XTemplate. Before writing code the image below shows the basic layout structure of the block that we will design for each List item. As you can see above we have a main <div> block which contains two <div> blocks inside it, the title <div> block and the body <div> block that will hold the product image and other details. Here is the XTemplate for our custom block var productTemplate = new Ext.XTemplate( '<tpl for=".">', '<div class="productBox">', '<div class="productTitle">', '{name}', '<img class="nextIcon" src="images/next.png"/>', '</div>', '<div class="productBody">', '<img class="productImage" src="{image_url}"/>',
  • 6. '<ol>', '<li>Price: {price}</li>', '<li>In Stock: {in_stock}</li>', '</ol>', '</div>', '</div>', '</tpl>' ); There are three items in the data so <tpl for=”.”> will loop three times each for one data object. And then it will put the values of the corresponding fields in the placeholders. As you can see in the code block we have a div box ofclassname = ‘productBox’. It holds two <div> blocks inside it, one for the title (class = ‘productTitle’) and the other for the body (class=’productBody’). The styles for them are all defined in the CSS which I will show later. You can also see in the code block the images that have been put together. Overall the code block is pretty simple and self-explanatory. Now lets bind the store, template to our list. This is how to do it var productList = new Ext.List({ styleHtmlContent:true, store: productStore, itemTpl: productTemplate, layout:'fit', height:"100%", emptyText:'Oops! No data' }); And then we can put our List in a Panel for it to display. Lets look at the full code and then I can explain more <!DOCTYPE html> <html> <head> <title>Custom List</title>
  • 7. <link href="css/sencha-touch.css" rel="Stylesheet" /> <script type="text/javascript" src="js/sencha-touch.js"></script> <script type="text/javascript"> Ext.setup({ tabletStartupScreen: 'tablet_startup.png', phoneStartupScreen: 'phone_startup.png', icon: 'images/homeblue.png', glossOnIcon: false, onReady: function(){ var productData = [ {"name": "iPod", "price": "$300", "image_url": "images/ipod.png", "in_stock": "yes"}, {"name": "Toaster", "price": "$200", "image_url": "images/toaster.png", "in_stock": "yes"}, {"name": "Clock", "price": "$120", "image_url": "images/clock.png", "in_stock": "no"}, ]; Ext.regModel('productModel', {fields: ['name','price','image_url','in_stock']}); var productTemplate = new Ext.XTemplate( '<tpl for=".">', '<div class="productBox">', '<div class="productTitle">',
  • 8. '{name}', '<img class="nextIcon" src="images/next.png"/>', '</div>', '<div class="productBody">', '<img class="productImage" src="{image_url}"/>', '<ol>', '<li>Price: {price}</li>', '<li>In Stock: {in_stock}</li>', '</ol>', '</div>', '</div>', '</tpl>' ); var productStore = new Ext.data.Store({ model: 'productModel', data: productData }); var productList = new Ext.List({ styleHtmlContent:true, styleHtmlCls:'testHtml', overItemCls:'testOver',
  • 9. selectedItemCls:'testSelect', pressedCls:'testPress', layout:'fit', height:"100%", emptyText:'Oops! No data', store: productStore, itemTpl: productTemplate }); //main viewport new Ext.Panel({ fullscreen:true, dockedItems:[{xtype:'toolbar', title:'Custom Product List'}], dock:'top', scroll:'vertical', items:[productList] }); } }); </script> </head> <body>
  • 10. </body> </html> We have pretty much discussed the things needed to create our custom product list. However, in the productList control above you can notice some CSS class properties that have been bolded. We have provided some CSS class names (for eg. testOver) for specific purpose. Here they are styleHtmlCls:'testHtml', overItemCls:'testOver', selectedItemCls:'testSelect', pressedCls:'testPress', You might ignore this for your custom List, but I will tell you that these are important. These are predefined CSS class names for the List control and by setting custom classes you can further control the look of your custom List. These are the definitions of the properties from the Sencha Touch API docs styleHtmlCls : String The class that is added to the content target when you set styleHtmlContent to true. This means that this CSS class will define the overall look of your list. overItemCls : String A CSS class to apply to each list item on mouseover selectedItemCls : String A CSS class to apply to each selected item in the list pressedCls : String A CSS class to apply to an item in the list while it is being pressed We will set the CSS styles for all these classes in our CSS block. Lets see our CSS block now <style> .productBox { border:1px solid #9a9a9a; }
  • 11. .productTitle { border-bottom:1px solid #9a9a9a; padding:5px 10px 0px 10px; background-color:#ccc; font-weight:bold; height:30px; } .nextIcon { float:right; } .productBody { padding:10px; } .productBody ol { float:right; }
  • 12. .productBody ol li { list-style:none; } .productImage { width:50px; } .testSelect { background-color:#efefef; } .testPress { /*I want that nothing should happen, so blank*/ } .testHtml { font-family:'Helvetica Neue', HelveticaNeue, Helvetica-Neue, Helvetica, 'BBAlpha Sans', sans-serif;
  • 13. font-size:15px; } .testOver { background-color:#aaaaaa; } </style> Simple CSS code, nothing fancy here. Note the custom CSS classes testOver, testHtml, testPress, testSelectdefined in the product List. We have put some CSS rules for them. Now, include this CSS block in your index page and we are ready to go. You should be able to see this at the end
  • 14. A Custom Product List Here is the demo application. Open it in your touch phone or test it in http://www.iphonetester.com/ which is an online iPhone simulator. This is it and we are good to go I guess.