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

发布于 2024-12-11 22:29:43 字数 673 浏览 0 评论 0原文

我想向每个 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/fsFNW/

I want to add a custom method to each of the Backbone classes - model, collection, router, view. How can I do that?

Here is what I am doing till now....

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");
};

I am guessing there must be a better and more elegant way to do this?

Update

Here's how I implemented it finally. Thanks for the advice about logging @dira

http://jsfiddle.net/fsFNW/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幸福丶如此 2024-12-18 22:29:43

要严格回答问题,请查看 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 函数并使用更重要的消息(“获取”、“渲染”等),因为“我来到这里:模型”不是很有用。

To strictly reply to the question, check out 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');

If you are using this for debugging, I recommend having a window.debug function and using more significant messages ("fetching", "rendering" etc) as "I came here: model" is not very useful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文