CanJS how to refresh a model

寵の児 提交于 2020-02-05 05:17:07

问题


I have a model which represents a list of jobs which are run on the server

I want to poll the server for updates on a timer to show changes to the state of the jobs.

How do I do this?

My Control looks like this

var control = Control({
        defaults: {
            view: 'app/views/job-index.ejs'
        }
    }, {
        init: function () {
            this.element
                .empty()
                .append(can.view(this.options.view, this.options));

            var options = this.options;
            window.setInterval(function() {
                options.result.refresh();
            }, 1000);
        },
    });

my model, so far looks like this

var model = can.Model({
        findOne: 'GET /api/jobs'
    }, {
        refresh: function() {
            // what goes here?
        }
    });

回答1:


One observation first:

If you are getting a collection of jobs you should probably want to use findAll instead of findOne:

findAll: 'GET /api/jobs',
findOne: 'GET /api/jobs/{id}'

I understand that result is a single record. So you can do something like:

var Model = can.Model({
    findAll: 'GET /api/jobs',
    findOne: 'GET /api/jobs/{id}'
    }, {
        refresh: function () {
            var id = this.attr('id');
            var self = this;

            Model.findOne({id: id}, function (model) {
                self.attr(model.attr());
            });
    }
});

Also, by convention you should name your model class Model not model.

Here is a fiddle http://jsbin.com/xarodoqo/4/edit



来源:https://stackoverflow.com/questions/22350543/canjs-how-to-refresh-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!