Jazerix
Jazerix

Reputation: 4801

Running functions on a data object

Basically, when I load my homepage, vue.js requests an api, that returns a json response like so

[
  {
    "time": 321
  },
  {
    "time": 2712
  }
]

When the request is finished loading, I assign the the array to a timers object in the data object in my vue.js file.

This is where it gets tricky. So basically, when above is loaded into vue, I need each one to be incremented each second, with setInterval(). To make it even worse, I need another callback for each function where I can pause the timer, and send another request to the server (to pause the timer serverside). Any ideas?

Upvotes: 1

Views: 381

Answers (1)

Jazerix
Jazerix

Reputation: 4801

I ended up creating a new timer that starts, when the document is loaded. To the response I've also added a counting attribute (boolean).

new Vue({
    el: "#body",

    data: {
        timers: [
            {
                time: 222,
                counting: true
            },
            {
                time: 4123,
                counting: true
            }
        ],
        test: 2
    },
    methods: {
        pauseTimer: function(timer) {
            timer.counting = !timer.counting;
        }
    },

    ready: function() {
        var that = this;
        var timer = setInterval(function(){
            $.each(that.$data.timers, function(index, value){
                if(value.counting)
                    value.time++;
            });
        }, 1000);
    }
});
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body id="body">
    <ul>
        <li v-repeat="timers">{{ time }} - <a href="#" v-on="click: pauseTimer(this)" v-text="counting ? 'Pause' : 'Start'"></a></li>
    </ul>
    {{ $data | json 2 }}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.10/vue.js"></script>
    
</body>
</html>

Upvotes: 1

Related Questions