Domanda

I've read every related post on this and spent last two days trying to figure out what I am doing wrong here without much success.

Working with this JS fiddle here as an example: http://jsfiddle.net/rniemeyer/dtpfv/ I am trying to implement a dirty flag. The only difference is that I am changing a data inside a regular span vs an input filed and using mapping plugin vs manually assigning observables.

$(document).ready(function(){

    ko.dirtyFlag = function(root, isInitiallyDirty) {
        var result = function() {},
            _initialState = ko.observable(ko.toJSON(root)),
            _isInitiallyDirty = ko.observable(isInitiallyDirty);

        result.isDirty = ko.computed(function() {
            return _isInitiallyDirty() || _initialState() !== ko.toJSON(root);
        });
        result.reset = function() {
            _initialState(ko.toJSON(root));
            _isInitiallyDirty(false);
        };
        return result;

    };

    $.getJSON('/environments/data.json', function(jsondata) {
        var mapping = {
            create: function (options) {
                var innerModel = ko.mapping.fromJS(options.data);
                for (var i=0; i < innerModel.deployments().length; i++) {
                    innerModel.deployments()[i].dirtyFlag = new ko.dirtyFlag(innerModel.deployments()[i]);
                }
                return innerModel;
            }
        }

        var viewModel = ko.mapping.fromJS(jsondata, mapping);

        self.save = function() {
            console.log("Sending changes to server: " + ko.toJSON(this.dirtyItems));  
        };

        self.dirtyItems = ko.computed(function() {
            for (var i = 0; i < viewModel().length;  i++ ) {
                return ko.utils.arrayFilter(viewModel()[i].deployments(), function(deployment) {
                    return deployment.dirtyFlag.isDirty();
                });
            }
        }, viewModel);

        self.isDirty = ko.computed(function() {
            return self.dirtyItems().length > 0;
        }, viewModel);

        self.changeTag = function (data, event) {

            // Neither .change() nor .trigger('change') work for me
            $(event.target).parents().eq(4).find('span.uneditable-input').text(data.tag).change()

            // This value never changes.
            console.log('Dirty on Change: '+self.dirtyItems().length)

        }

        ko.applyBindings(viewModel);

    });

})

Here is stripped down piece of the HTML that triggers the changeTag() function, which replaces current_tag() with a selection from the drop down menu. This, however, does not trigger KnockoutJS update.

<div>
    <span data-bind="text: current_tag() }"></span>
    <div>
        <button data-toggle="dropdown">Select Tag</button>
        <ul>
          <!-- ko foreach: $.parseJSON(component.available_tags() || "null") -->
          <li><a href="#" data-bind="click: function(data, event) { changeTag(data, event) }"></a></li>
          <!-- /ko -->
        </ul>
    </div>
</div>

I am on day two of trying to figure this out. Any idea what I am doing wrong here? Am i supposed to use an input field and not a regular span element? Do i need to be changing values my viewModel directly instead of using jQuery to manipulate DOM? (I have actually tried that, but changing viewModel and then re-binding to it seems to slow things down, unless I am doing it wrong)

Thank you.

È stato utile?

Soluzione

As said in the comments, it is considered 'bad Knockout practise' to update a value through jQuery, when you can also update the observable directly. Knockout promotes a data-driven approach.

In response to your last comment (not sure yet how to answer comments on stack overflow): the reason the UI isn't picking up the change is because you assigned the value wrong:

var x = ko.observable(1); // x is now observable
x = 3; // x is no longer observable. After all, you've assigned the value 3 to it. It is now just a number
x(3); // this is what you're after. x is still an observable, and you assigned a new value to it by using Knockout's parentheses syntax. If x is bound to the ui somewhere, you'll see the value 3 appear

So you want to do

jsondata[environment()].deployments[deployment()].current_tag(ko.dataFor(event.target).tag);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top