在Backbone中共享相同功能的最佳方法

在Backbone中共享相同功能的最佳方法

问题描述:

我目前处于这种情况:对于Backbone.Collection(但对于Backbone.Model也应该如此),我以这种方式扩展了类(1).
我要分享的功能如下:
1)startPollingstopPolling应该是可从所有Backbone.Collections以及最终Backbone.Models
访问的公共方法 2)executePollingonFetch应该是私有方法.

I am in the current situation: for a Backbone.Collection (but it should be also for a Backbone.Model), I extend the class in this way(1).
The functionality I want to share are the following:
1) startPolling and stopPolling should be public method accessible from all Backbone.Collections and eventually Backbone.Models
2) executePolling and onFetch should be private method.

在所有Backbone.Collection/Backbone.ModelonFetch私有方法之间共享startPollingstopPolling的最佳方法是什么?

What is the best way to share startPolling and stopPolling between all Backbone.Collection/Backbone.Model keeping executePolling and onFetch private method?

我的想法是创建一个新文件utils/backbone.polling.js(2).是好的解决方案吗?

My idea is to create a new file utils/backbone.polling.js(2). Is it good solution?

(1)

define([
    'backbone',
    'models/myModel'
], function (Backbone, MyModel) {
    'use strict';

    var MyCollection = Backbone.Collection.extend({

        model: MyModel,

        url: 'some_url'

        initialize : function () {
            _.bindAll(this);
        },

        startPolling: function () {
            this.polling = true;
            this.minutes = 2;
            this.executePolling();
        },

        stopPolling: function () {
            this.polling = false;
        },

        executePolling: function () { 
            this.fetch({success : this.onFetch});
        },

        onFetch: function () {
            if (this.polling) {
                setTimeout(this.executePolling, 1000 * 60 * this.minutes);
            }
        }
    });

});


(2)


(2)

utils/backbone.polling.js

Backbone.Collections.startPolling = function () {
    // code here
};

Backbone.Collections.stopPolling = function () {
    // code here
};

尽管@Flops和@jakee的方法非常优雅,但一个非常简单的方法就是拥有一个纯JS utils库,例如:

Despite the very elegant approaches of @Flops and @jakee a very simple one could be having a pure JS utils library like:

// code simplified and no tested
App = {};
App.Utils = {};
App.Utils.startPolling: function () {
  this.polling = true;
  this.minutes = 2;
  this.executePolling();
},

var MyCollection = Backbone.Collection.extend({
  startPolling: App.Utils.startPolling;
});