我目前处于这种情况:对于Backbone.Collection
(但它也应该是Backbone.Model
),我以这种方式扩展类(1)。
我想分享的功能如下:
1)startPolling
和stopPolling
应该从所有Backbone.Collections访问的公共方法,并最终Backbone.Models
2)executePolling
和onFetch
应该是私有的方法。在Backbone中共享相同功能的最佳方式
什么是共享所有Backbone.Collection/Backbone.Model
保持executePolling
和onFetch
私有方法之间startPolling
和stopPolling
的最佳方式?
我的想法是创建一个新文件utils/backbone.polling.js
(2)。这是好的解决方案吗?
(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)
utils/backbone.polling.js
Backbone.Collections.startPolling = function() {
// code here
};
Backbone.Collections.stopPolling = function() {
// code here
};