Array
. Distinctive features are: the presence of a change
event to track any changes in the array, and the methods insert()
, update()
, remove()
, set()
, get()
for simplified work with the array. All the native methods of the standard Array
.
var fruits = new Arr('apple', 'orange', 'pineapple'); fruits.on('change', function(event) { alert('I changed fruits: ' + fruits.join(', ')); }); fruits.push('banana');
var fruits = new Arr('apple', 'orange', 'pineapple'); fruits.get(0); // apple fruits.get(10, 'lime'); // trying to get undefined element - return defaultValue // lime fruits.get(20); // trying to get undefined element // null fruits.set(1, 'nut'); // ['nut', 'orange', 'pineapple'] fruits.insert(['lime', 'banana', 'kivi']); // ['nut', 'orange', 'pineapple', 'lime', 'banana', 'kivi'] fruits.remove(function(item, index) { if (item.indexOf('apple') !== -1) { // remove only items where word "apple" is founded return true; } }); // ['nut', 'orange', 'lime', 'banana', 'kivi'] fruits.update(function(item, index) { if (item.indexOf('nut') !== -1) { // update "nut" to "apple" return 'apple'; } }); // ['apple', 'orange', 'lime', 'banana', 'kivi']
change
.
var fruits = new Arr('apple', 'orange', 'pineapple'); fruits.on('change', function(event) { // handler console.log(event); }); fruits.push('banana'); // { "type": "insert", "items": ["banana"] } fruits.remove(function(item) { return item == 'banana'; }); // { "type": "remove", "items": ['banana"] }
handler
object, event
. The properties of the event
: type
object can be: insert
, update
, remove
. The items
property lets you know which elements of the array were affected.
// var weatherList = new Arr; // - weatherList.on('change', function() { var el = $('#weather'); var celsius, maxCelsius, minCelsius, weather; el.html(''); weatherList.forEach(function(item) { celsius = Math.floor(item.main.temp - 273); maxCelsius = Math.floor(item.main.temp_max - 273); minCelsius = Math.floor(item.main.temp_min - 273); weather = item.weather.pop().main; el.append('<li><b>' + item.name + '</b> ' + ' ' + celsius + ' (max: ' + maxCelsius + ', min: ' + minCelsius + ') ' + weather + '</li>'); }); }); // , weatherList function loadWeather(lat, lng) { $.get('http://api.openweathermap.org/data/2.5/find?lat=' + lat + '&lon=' + lng + '&cnt=10').done(function(data) { // clear weather list weatherList.remove(function() { return true; }); // insert items weatherList.insert(data.list); }); } // loadWeather(50.4666537, 30.5844519);
Array
.
removeListener()
method.
Source: https://habr.com/ru/post/238197/