简体   繁体   中英

Knockout.js: highlight text box on value change from code

I'm using Knockout.js in my ASP.NET MVC4 project in combination with SignalR for a realtime visualization of industrial facilities. We have many pages where spans or text boxes are data-bound to a view model. Every 2 to 10 seconds a new value is sent from the server to the clients browser via SignalR and the value in the view model (and thereby the text in the span, div or text box input) gets updated. This works very well. What I'm trying to achive is some kind of visual notification on the page (eg jQuery-highlight the DOM element that displays the value) whenever a value changes.

I guess the knockout.js event-binding is close to what I need, but as far as I can see it can only pass the relevant view model item to a JS function, not the DOM element that I would need to highlight. I hope I got the idea across.

So what I need is a way to trigger a function when the value of a text box input gets changed from "code behind" and not from manual user input. This function should be given the concerning DOM element for further processing.

My code so far:

    <table class="StatusRowList">
        <thead>
            <tr>
                <th>Parameter</th>
                <th>Value</th>
            </tr>
        </thead>
        <tbody data-bind="foreach: Items">
            <tr>
                <td><a data-bind="attr: { href: '/Archive/Show/?StationId=' + StationId() + '&DataPointId=' + DpId() }"><span data-bind="text: Text"></span></a></td>
                <td>
                    <span data-bind="text: UnitPrefix"></span>
                    <input data-bind="value: Value" />
                    <span data-bind="text: UnitSuffix"></span>
                </td>
            </tr>
        </tbody>
    </table>

The line of interest is the "input" between the two spans. Thanks for help on that!

There is no way to distinct if a observable was set from a binding or from a ViewModel. You will have to write a ko extender that fixes this something like

http://jsfiddle.net/a3fFa/

ko.extenders.eventDriven = function(target, options) {
    var computed = ko.computed({
        read: target,
        write: target
    });
    computed.updatedFromEvent = ko.observable(false);
    computed.onEvent = function(value) {
        target(value);
        computed.updatedFromEvent(true);
    }    

    return computed;
};

edit: I did a framework for this btw, https://github.com/AndersMalmgren/Knockout.Concurrency But its more aimed to detecing when another user saves and present the conflicts to the user http://jsfiddle.net/7atZT/1/

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