vendredi 3 juillet 2015

In JavaScript, is it a good practice to depend on object references to "listen" for changes?

I have to implement a repository pattern-like object that will maintain a list of items. The repo would look something like this:

var repository = {

    data: [],

    getAll: function() {
        return this.data;
    },

    update: function() { ... }
}

The end consumer of the repo's data would be some component. I am thinking to exploit the reference to the repo's data array in order to update the DOM whenever it changes:

function ItemList() {
    this.data = repository.getData();

    when (this.data is changed) {
        update the view
    }

    this.userInput = function() {
        repository.update();
    }
}

While it feels neat and supposedly uses a legit functionality, is it really a good idea? Should I use observer/notifications in the repository instead?

var repository = {
    ...
    onDataChange: function(callback) { ... }
}

An example (using Angular) you can find here: http://ift.tt/1NDqe2P

Aucun commentaire:

Enregistrer un commentaire