【问题标题】:backbone.js: how to add a custom method to each backbone class骨干.js:如何为每个骨干类添加自定义方法
【发布时间】:2011-10-25 09:56:53
【问题描述】:

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

【问题讨论】:

    标签: backbone.js


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 2012-11-23
      • 2013-10-14
      • 2011-11-26
      • 2011-10-18
      • 2013-01-16
      • 1970-01-01
      相关资源
      最近更新 更多