在 Backbone.js 和 Underscore.js 中绑定回调

发布于 2025-01-07 09:27:31 字数 499 浏览 3 评论 0原文

我有以下代码:

  initialize: function() {
    _.bindAll(this);

    var callBack = function(res) {
      window.item = new Item(res);
      this.render();
    };

    _.bind(callBack, this);

    $.get('/item/parse', {
      uri: decodeURIComponent($.urlParam('uri')),
      title: decodeURIComponent($.urlParam('title'))
    },
      callBack
    );
  },

目的是在 $.get 函数完成后调用 render() 。但是,即使在使用 _.bind 绑定回调函数之后,我仍然在控制台中收到“Object has no function render”。我在这里使用绑定不正确吗?

I have the following code:

  initialize: function() {
    _.bindAll(this);

    var callBack = function(res) {
      window.item = new Item(res);
      this.render();
    };

    _.bind(callBack, this);

    $.get('/item/parse', {
      uri: decodeURIComponent($.urlParam('uri')),
      title: decodeURIComponent($.urlParam('title'))
    },
      callBack
    );
  },

The intention is that render() should be called after the $.get function finishes. However, even after binding the callback function with _.bind, I still get "Object has no function render" in the console. Am I using bind incorrectly here?

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

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

发布评论

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

评论(2

兮颜 2025-01-14 09:27:31

_.bind 返回一个新函数,因此:

callBack = _.bind(callBack, this);

您也可以使用 _.bindAll,但您必须在定义函数之后调用它。否则,在调用 _.bindAll 时不会有任何函数。请注意,在这种情况下,您必须使用 this.callBack = ...,否则 this 将不会包含任何函数。

同时使用 _.bind_.bindAll 是多余的。

_.bind returns a new function, so:

callBack = _.bind(callBack, this);

You can also use _.bindAll, but you have to call it after you define the function. Otherwise there are no functions at the time you call _.bindAll. Note that you have to use this.callBack = ... in that case, because otherwise this won't consist of any functions.

Using both _.bind and _.bindAll is superfluous.

挥剑断情 2025-01-14 09:27:31

我通常在模型上编写一个“加载”方法,并提供回调作为参数。然后我从视图中的 render() 方法调用此方法,并在回调函数中执行我需要执行的操作(当然,该回调是在数据加载后在模型中触发的)。

I usually write a 'load' method on my model which I giva a callback as parameter. Then I call this method from the render() method in the view and do whatever I need to do in the callback function (of course, that callback is triggered in the model after the data has been loaded).

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