Loading
 
What's Next: View All Tutorial →

Extjs Iterator Function

Ext JS has a number of handy iterator functions. Some, like Ext.each, you probably already know about, but there are a few others lurking around which can be useful in saving yourself a few lines of code. First, let’s recap Ext.each: Ext.each ...

Published Date: 07/09/2014  Last Modified Date: 07/09/2014    New Post



Ext JS has a number of handy iterator functions. Some, like Ext.each, you probably already know about, but there are a few others lurking around which can be useful in saving yourself a few lines of code. First, let’s recap Ext.each:

Ext.each

var people = ['Bill', 'Saul', 'Gaius'];
 
//using each to detect Cylons:
Ext.each(people, function(person, index) {
  var cylon = (index + 1) % 2 == 0; //every second man is a toaster
  alert(person + (cylon ? ' is ' : ' is not ') + 'a fraking cylon');
});
 
//is the same as
for (var i=0; i < people.length; i++) {
  var person = people[i];
  var cylon = (i + 1) % 2 == 0; //every second man is a toaster
 
  alert(person + (cylon ? ' is ' : ' is not ') + 'a frakin cylon');
};

Ext.iterate

var ships  = {'Bill': 'Galactica', 'Laura': 'Colonial One'};
 
Ext.iterate(ships, function(key, value) {
  alert(key + "'s ship is the " + value);
});
 
//is the same as
for (key in ships) {
  var value = ships[key];
  alert(key + "'s ship is the " + value);
}

Ext.pluck

Ext.pluck grabs the specified property from an array of objects:
var animals = [
  {name: 'Ed', species: 'Unknown'},
  {name: 'Bumble', species: 'Cat'},
  {name: 'Triumph', species: 'Insult Dog'}
];
 
Ext.pluck(animals, 'species'); //returns ['Unknown', 'Cat', 'Insult Dog']
Ext.pluck(animals, 'name'); //returns ['Ed', 'Bumble', 'Triumph']

Ext.invoke

Invoke allows a function to be applied to all members of an array, and returns the results. Using our animals object from above:

var describeAnimal = function(animal) {
  return String.format("{0} is a {1}", animal.name, animal.species);
}
 
var describedAnimals = Ext.invoke(animals, describeAnimal);
console.log(describedAnimals); // ['Ed is a Unknown', 'Bumble is a Cat', 'Triumph is a Insult Dog'];

Ext.partition

Ext.Partition splits an array into two sets based on a function you provide:
var trees = [
  {name: 'Oak',    height: 20},
  {name: 'Willow', height: 10},
  {name: 'Cactus', height: 5}
];
 
var isTall = function(tree) {return tree.height > 15};
 
Ext.partition(trees, isTall);
 
//returns:
[
  [{name: 'Oak', height: 20}],
  [{name: 'Willow', height: 10}, {name: 'Cactus', height: 5}]
]



 
Awaiting for Administrator approval





Tags: Basic

← Back to list


Related Post




×