简体   繁体   中英

Knockoutjs does not update viewmodel

In my view I have file input:

<input type="file" class="file-input" name="file_source" size="40"  onchange=''>

And span, in which I am showing the uploaded filename:

<span class='label label-info' id="upload-file-info" data-bind="text: image"></span>

$(".file-input").change(function() {
           var elem = $("#upload-file-info");
           elem.html = $(this).val();
        });

This span is binded with knockoutjs:

viewModel = {
image: ko.observable()
}

ko.applyBindings(viewModel);

The problem is that the observable do not updates when I update the span text. Althought I have the filename in the span, the observable is empty. How can I make the observable to update itself when the span text changes ?

I did a quick fiddle according to my comment on your question. This should work:

jQuery(document).ready(function ($) {
    'use strict';

    $(".file-input").change(function () {
        var elem = $("#upload-file-info");
        viewModel.image($(this).val());
    });

    var viewModel = {
        image: ko.observable()
    };
    viewModel.image.subscribe(function (value) {
        alert(value);
    });

    ko.applyBindings(viewModel);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM