Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js observableArray vs Backbone.js Collection - What's the difference?

In Knockout.js I create an observableArray to push models into:

function Room(data) {
        this.name = ko.observable(data.name);

    }   


    function RoomViewModel() {      
        var self = this;
        self.rooms = ko.observableArray([]);
        self.newRoomText = ko.observable();         

        self.addRoom = function() {
            self.rooms.push(new Room({ name: this.newRoomText() }));
            self.newRoomText("");       
            $("#modal").dialog("close");        
        }.bind(self);           
    }

In Backbone.js I would create a collection to store my models:

var Book = Backbone.Model.extend();

var Books = new Backbone.Collection([
  {name: "Abe Lincoln - Vampire Hunter"}
  {name: "Pride and Prejudice and Zombies"}
]);

Just how different are these 2 structures from each other?

What exactly is going on behind the scenes to make these data structures different from a standard Javascript Array?

like image 952
PhillipKregg Avatar asked Jan 18 '23 21:01

PhillipKregg


1 Answers

This is a difficult question to fully answer but here is my take on it :).

Backbone.js Collection:

  • fetching models from the server
  • triggering change/add/remove events
  • listening to model events and triggering them on collections
  • automatic validation of the models
  • lot of cross-browser convience methods for working with collections (each, max, sort, reduce, etc.)

Knockout.js observableArray:

  • tracks added and removed elements - updates UI automatically
  • cross-browser implementation of the array's methods (e.g. IE8 has problems w/ native .indexOf())
  • convience destroy & destroyAll methods for Rails developer that will set _destroy property on objects to true - this will inform Rail's ActiveRecord which objects should be deleted.

Backbone.Collection is working with the Backbone.js framework and observableArray only with Knockout.js. There is no real in comparing them with each other in a isolation because they are part of a framework and if your application is built on Backbone you cannot use observableArray and vice versa.

If you want to know what exactly is going on behind the scenes then here is the source code:

  • Backbone.Collection
  • obervableArray
like image 186
kubetz Avatar answered Jan 20 '23 11:01

kubetz