最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Binding a callback in Backbone.js and Underscore.js - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Feb 19, 2012 at 13:40 JamesJames 6,50911 gold badges61 silver badges87 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

_.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.

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).

发布评论

评论列表(0)

  1. 暂无评论