Binding a callback in Backbone.js and Underscore.js

点点圈 提交于 2019-12-10 20:23:16

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/9349666/binding-a-callback-in-backbone-js-and-underscore-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!