Arr.js: events for a standard array

    Arr.js is a “class” inherited from the standard Array. Features include: the presence of events changeto track any changes in the array, and methods of insert(), update(), remove(), set(), get()for easy working with an array. All the "native" methods of the standard are available Array.

    var fruits = new Arr('apple', 'orange', 'pineapple');
    fruits.on('change', function(event) {
      alert('I changed fruits: ' + fruits.join(', '));
    });
    fruits.push('banana');
    


    Code: Examples of basic methods
    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']
    



    Why change event and how to work with them


    The presence of an event allows you to do:
    • similarity to FRP: when a change in some data should entail a change in other data and so on
    • deferred rendering: something has changed in the array - updated HTML (ala angular)
    • automatic saving of data to the server in case of any changes

    One event is supported 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"] }
    

    To understand what happened in the array can be transmitted on to the handlerobject event. Object Properties event: typecan be: insert, update, remove. The property itemsallows you to find out which elements of the array were affected.

    Good example


    // Массив в котором планируем хранить данные о погоде
    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('
  • ' + item.name + ' ' + ' ' + celsius + ' (max: ' + maxCelsius + ', min: ' + minCelsius + ') ' + weather + '
  • '); }); }); // Загрузка погоды из сервиса, обновление массива 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);

    View a working example on JSBin .

    In custody


    I want to add that the idea is not new, there is github: // MatthewMueller / array . But the code seemed to me too overloaded, which in fact can lead to performance problems. Therefore, it was decided to "expand" the standard Array.

    Plans: there is a desire to cover the library with high-quality tests - it would be nice if anyone, who is well versed in this, helped.

    It is not planned to expand the list of methods, with the exception of the method removeListener().

    Arr.js repository and documentation (en) .

    Comments on improvements are welcome!

    PS: For personal purposes, the component https://github.com/jmas/list/blob/master/List.js was developedwhich uses Arr.js. The component is used to create lists that independently update HTML when the data array changes. The component uses componentjs to resolve dependencies.

    Also popular now: