覆盖 Backbone.sync 但保存其以前的功能

发布于 2024-12-10 02:11:16 字数 111 浏览 1 评论 0原文

我想覆盖 Backbone.sync,但也希望在添加后运行原始 Backbone.sync 功能。我想有点像在 Java 中调用超类的 super 。除了复制所有以前的代码之外,还有其他方法可以做到这一点吗?

I'd like to override Backbone.sync but also have the original Backbone.sync functionality run after my additions. I guess kind of like calling super on a superclass in Java. Is there a way to do this other than copying all the previous code over?

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

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

发布评论

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

评论(2

梨涡少年 2024-12-17 02:11:16

在 JavaScript 中,您可以将任何属性或方法存储在变量中。以下示例将 Backbone.sync 分配给另一个变量,然后在函数末尾使用传递给新 Backbone.sync 函数的所有变量调用它。

var originalSync = Backbone.sync;
Backbone.sync = function() {
    // Your code here.
    return originalSync.apply(Backbone, arguments);
};

In JavaScript, you can store any property or method in a variable. The following example will assign Backbone.sync to another variable and then at the end of your function call it with all the variables that are passed to your new Backbone.sync function.

var originalSync = Backbone.sync;
Backbone.sync = function() {
    // Your code here.
    return originalSync.apply(Backbone, arguments);
};
九公里浅绿 2024-12-17 02:11:16

上面 Brian Nickel 提供的答案实际上会覆盖Backbone同步 方法,该方法会影响所有 Backbone 模型。如果您想要覆盖单个模型类型的 sync ,您可能更喜欢以下模式(同时确保使用来自 sync 的正确签名覆盖 sync a href="http://backbonejs.org/#Sync" rel="nofollow noreferrer">Backbone 文档):

var YourModel = Backbone.Model.extend({
    sync: function(method, model, options) {
        // do your custom work here
        return Backbone.Model.prototype.sync.call(this, method, model, options);
    }
});

有关其工作原理的更完整信息,请参阅Backbone 的带注释的源代码本身。希望有帮助。

The answer provided by Brian Nickel above will actually override Backbone's sync method, which will affect all Backbone models. If what you had in mind is to override sync for an individual model type, you may prefer instead the following pattern (also making sure to override sync with the correct signature from the Backbone docs):

var YourModel = Backbone.Model.extend({
    sync: function(method, model, options) {
        // do your custom work here
        return Backbone.Model.prototype.sync.call(this, method, model, options);
    }
});

For more complete information about how this works, please refer to Backbone's annotated source itself. Hope that helps.

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