有没有办法在骨干网中创建一个私有函数,以便它只暴露给模型本身并且还可以访问this?
我该如何updateTime私密?
var Timeline = Backbone.Model.extend({
url: 'servertime/',
start: function(){
this.fetch({
success: function(timeline, response){
timeline.updateTime();
setInterval(function() {
timeline.updateTime();
}, 60 * 1000);
}
});
},
updateTime: function(){ //How can I make this private?
this.time = ...
}
});
Run Code Online (Sandbox Code Playgroud)
ale*_*lex 14
你可以通过将它全部包装在一个自动调用的匿名函数中来实现这一点,这样你就可以确保updateTime是私有的:
(function() {
var updateTime = function(){ // this stays private to this anonymous function
this.time = ...
},
Timeline = Backbone.Model.extend({
url: 'servertime/',
start: function(){
this.fetch({
success: function(timeline, response){
updateTime.call(timeline);
setInterval(function() {
updateTime.call(timeline);
}, 60 * 1000);
}
});
}
});
})();
Run Code Online (Sandbox Code Playgroud)
你可以做updateTime一个私人的功能,但不是私人的方法.我还建议在前置下划线以明确它是一个私有函数.
(function() {
function _updateTime(timeline){
timeline.time = ...
}
Timeline = Backbone.Model.extend({
url: 'servertime/',
start: function(){
this.fetch({
success: function(timeline, response){
_updateTime(timeline);
setInterval(function() {
_updateTime(timeline);
}, 60 * 1000);
}
});
}
});
})();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5945 次 |
| 最近记录: |