[英]backbone.js: how to add a custom method to each backbone class
我想向每個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");
};
我猜想必須有一種更好,更優雅的方法來做到這一點?
更新
這就是我最終實現它的方式。 感謝您提供有關記錄@dira的建議
要嚴格回答該問題,請訪問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函數,並使用更重要的消息(“獲取”,“呈現”等),因為“我來這里:模型”不是很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.