backbone.js:如何为每个骨干类添加自定义方法

vik*_*tra 2 backbone.js

我想为每个Backbone类添加一个自定义方法 - 模型,集合,路由器,视图.我怎样才能做到这一点?

这是我到现在为止所做的......

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");
};
Run Code Online (Sandbox Code Playgroud)

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

更新

这是我最终实现它的方式.感谢关于记录@dira的建议

http://jsfiddle.net/fsFNW/

dir*_*ira 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');
Run Code Online (Sandbox Code Playgroud)

如果您使用它进行调试,我建议使用window.debug函数并使用更重要的消息("获取","渲染"等)作为"我来到这里:模型"不是很有用.