Search code examples
knockout.jsobservableko.observablearray

Knockout: can't we just use observable instead of observablearray


giving the fact that a JavaScript array is specific type of an javascript object (an associative array), can't we just use ko.observable() instead of ko.observableArray()? especially if we are NOT interested in observing changes in an array properties like length...

As an exemple, in these tasklist-based knockout projects, we would just add a new task as following

tasklist[newtask.title]=newtask.description

in the object (an associative array). is it correct?

here a string example http://jsfiddle.net/zfjqd6oa/


Solution

  • @origineil thank you for you r proposition. yes this is exactly what i was looking for. This way I'll be able to access directly my "specific item" (as an associative array ) http://jsfiddle.net/xgup9Lsv/

    var SimpleListModel = function () {
        var self = this;
        self.items = ko.observable({});
        self.itemToAdd = ko.observable("");
        self.addedItems = ko.computed(function(){
             return Object.keys(self.items())});
        self.addItem = function () {
            console.log("add")
            if (self.itemToAdd() != "") {
                var addition =  self.itemToAdd()
                self.items()[addition] = addition
                self.items.valueHasMutated()
            }
        } 
    };
    
    var model = new SimpleListModel()
    ko.applyBindings(model);