2011-10-25 60 views
2

我想为每个骨干类 - 模型,集合,路由器,视图添加自定义方法。我怎样才能做到这一点?backbone.js:如何向每个骨干类添加自定义方法

下面是我在做什么,直到如今....

Backbone.Router.prototype.method1 = function() { 
    console.log("I came here: router"); 
}; 
Backbone.View.prototype.method1 = function() { 
    console.log("I came here: view"); 
}; 
Backbone.Model.prototype.method1 = function() { 
    console.log("I came here: model"); 
}; 
Backbone.Collection.prototype.method1 = function() { 
    console.log("I came here: collection"); 
}; 

我猜必须有一个更好,更优雅的方式来做到这一点?

更新

这里是我是如何实现它最后。感谢有关记录@dira建议

http://jsfiddle.net/fsFNW/

回答

6

要严格解答问题,请http://jsfiddle.net/dira/bbnSE/

window.debug_factory = function(kind) { 
    return function(message) { 
     console.log("I came here: " + kind + " " + " " + message); 
    } 
}; 

Backbone.Model.prototype.debug  = window.debug_factory('model'); 
Backbone.Collection.prototype.debug = window.debug_factory('collection'); 

Course = Backbone.Model.extend({}); 
Courses = Backbone.Collection.extend({model: Course}); 

c1 = new Course({name: 'c1'}); 
courses = new Courses(); 
courses.add(c1); 

c1.debug('a'); 
courses.debug('b'); 
c1.debug('c'); 

如果您正在使用这个用于调试,我建议您在window.debug功能并使用更重要的信息(“提取”,“渲染”等),因为“我来到这里:模型”并不是很有用。