How can i constantly update a value databinded to

2019-08-26 04:33发布

I am to create an inbox messages drop down like this,

enter image description here

were the relative time of the message gets displayed via moment JS. The following snippet below shows the final result. but the problem with this code is that the time which is in milliseconds does not get updated at interval to show the relative time of the milliseconds with the present date. So i tried using set interval inside the method.

Non Set interval Example (works fine, but the final converted time doesnt change after being changed the first time)

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>

<table>
        <thead>
            <tr><th>First name</th><th>Last name</th></tr>
        </thead>
        <tbody data-bind="foreach: people">
            <!-- ko if: ($index() < 5) -->
            <tr>
                <td data-bind="text: firstName"></td>
                <td data-bind="text: message"></td>
                <td data-bind="text: $root.converttime(dateCreated)"></td>
            </tr>
            <!-- /ko -->
        </tbody>
    </table>

    
    <script type="text/javascript">
        var viewmodel = {
            people: ko.observableArray([
                { firstName: 'Bert', message: 'Bertington', dateCreated:1540887096175 },
                { firstName: 'Charles', message: 'Charlesforth',dateCreated:1540887096175 },
                { firstName: 'Author', message: 'Dentiste', dateCreated:1540887096175 }
                
            ])
        };
        viewmodel.converttime = function (milliseconds){
        
      
        
        return moment(milliseconds).fromNow();

         
        };
        ko.applyBindings(viewmodel);
        
    </script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

With Set Interval Example : but the result is awkward

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>

<table>
        <thead>
            <tr><th>First name</th><th>Last name</th></tr>
        </thead>
        <tbody data-bind="foreach: people">
            <!-- ko if: ($index() < 5) -->
            <tr>
                <td data-bind="text: firstName"></td>
                <td data-bind="text: message"></td>
                <td data-bind="text: $root.converttime(dateCreated)"></td>
            </tr>
            <!-- /ko -->
        </tbody>
    </table>

    
    <script type="text/javascript">
        var viewmodel = {
            people: ko.observableArray([
                { firstName: 'Bert', message: 'Bertington', dateCreated:1540887096175 },
                { firstName: 'Charles', message: 'Charlesforth',dateCreated:1540887096175 },
                { firstName: 'Author', message: 'Dentiste', dateCreated:1540887096175 }
                
            ])
        };
        viewmodel.converttime = function (milliseconds){
        
        return setInterval(function()
        {
        
          return moment(milliseconds).fromNow();

        }, 3000);
      
        
       

         
        };
        ko.applyBindings(viewmodel);
        
    </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>

1条回答
姐就是有狂的资本
2楼-- · 2019-08-26 05:27

Here's the approach I often take:

You can create a clock class/object that exposes a moment wrapped in an observable. The clock takes care of updating this moment every x ms.

Whenever you use this moment inside a computed, you have an automatically updating value!

const Clock = (freq) => {
  let active = null;
  const now = ko.observable(moment());
  const tick = () => now(moment());
  const loop = () => {
    active = setTimeout(loop, freq);
    tick();
  }
  
  return {
    now: ko.pureComputed(now), // read only
    start: loop,
    stop: () => clearInterval(active)
  }
};


function App() {
  
  const clock = Clock(1000);
  const creationTime = moment();
  const launchTime = moment().add(1, "minute");
  
  this.countDown = ko.pureComputed(
    () => launchTime.from(clock.now())
  );
  
  this.stopwatch = ko.pureComputed(
    () => clock.now().diff(creationTime, "seconds")
  );
  
  clock.start();
}

ko.applyBindings(new App());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<p>Time till launch: <code data-bind="text: countDown"></code></p>
<p>Time elapsed: <code data-bind="text: stopwatch"></code></p>

Here's an example with your data:

const Clock = (freq) => {
  let active = null;
  const now = ko.observable(moment());
  const tick = () => now(moment());
  const loop = () => {
    active = setTimeout(loop, freq);
    tick();
  }

  return {
    now: ko.pureComputed(now), // read only
    start: loop,
    stop: () => clearInterval(active)
  }
};

const Message = (clock, msgData) => ({
  firstName: msgData.firstName,
  message: msgData.message,
  timeIndicator: ko.pureComputed(
    () => moment(msgData.dateCreated).from(clock.now())
  )
});

const App = () => {
  const clock = Clock(100);
  clock.start();

  return {
    messages: ko.observableArray(
      getMsgData()
        .map(msgData => Message(clock, msgData))
    )
  }
};

ko.applyBindings(App());

function getMsgData() {
  return [{
      firstName: 'Bert',
      message: 'Bertington',
      dateCreated: Date.now()
    },
    {
      firstName: 'Charles',
      message: 'Charlesforth',
      dateCreated: 1540889093175
    },
    {
      firstName: 'Author',
      message: 'Dentiste',
      dateCreated: 1540887096175
    }

  ]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<h2>Messages</h2>
<ul data-bind="foreach: messages">
  <li>
    <em data-bind="text: timeIndicator"></em><br/>
    <strong data-bind="text: firstName"></strong>: <span data-bind="text: message"> </span>
  </li>
</ul>

查看更多
登录 后发表回答