knockoutjs how to call applybindings with viewmodel function indirectly

This should be an easy question, but I just can't figure out how to do it or find the right answer. I'm trying to implement the changeTracker here but I have a viewModel function, not just a variable. I'm currently using

var viewModel = function () {
    // code
}

and applying bindings using

var vm = new viewModel();
ko.applyBindings(vm);

How do I incorporate the changeTracker into my application? I tried

var vm = new changeTracker(viewModel());

and

var vm = new changeTracker(new viewModel());

but neither works. The changeTracker fiddle html is:

<p>Text property: <input data-bind="value: someTextProperty" /></p>
<p>Bool property: <input type="checkbox" data-bind="checked: boolProperty" /></p>
<p>Array items count: <span data-bind="text: arrayItems().length"></span> <button data-bind="click:addItem">Add</button></p>

<hr/>

<p>Something has changed? <b data-bind="text: tracker().somethingHasChanged() ? 'YES' : 'NO'"></b></p>
<button data-bind="click: tracker().markCurrentStateAsClean, enable: tracker().somethingHasChanged">
    Mark current state as clean
</button>

and the javascript is:

function changeTracker(objectToTrack, hashFunction) {    
    hashFunction = hashFunction || ko.toJSON;
    var lastCleanState = ko.observable(hashFunction(objectToTrack));

    var result = {
        somethingHasChanged : ko.dependentObservable(function() {
            return hashFunction(objectToTrack) != lastCleanState()
        }),
        markCurrentStateAsClean : function() {
            lastCleanState(hashFunction(objectToTrack));   
        }
    };

    return function() { return result }
}

var viewModel = {
    someTextProperty: ko.observable("Hello"),
    boolProperty: ko.observable(false),
    arrayItems: ko.observableArray([]),

    addItem : function() { this.arrayItems.push("Another") }
};
viewModel.tracker = new changeTracker(viewModel);
ko.applyBindings(viewModel);

Upvotes: 0

Views: 178

Answers (1)

Robert Slaney
Robert Slaney

Reputation: 3722

I changed the jsFiddle is use a constructor function and it works without issue. You attach changeTracker to the viewModel, you don't use the changeTracker instance returned as the bound viewModel.

var ViewModel = function() {
    this.someTextProperty = ko.observable("Hello");
    this.boolProperty = ko.observable(false);
    this.arrayItems = ko.observableArray([]);

    this.addItem = function() { this.arrayItems.push("Another"); };
};
var viewModel = new ViewModel();
viewModel.tracker = new changeTracker(viewModel);
ko.applyBindings(viewModel);

Upvotes: 1

Related Questions