Calling a jQuery plugin in a Backbone render method

前端 未结 5 1733
隐瞒了意图╮
隐瞒了意图╮ 2021-02-02 16:09

I have a render method in Backbone that goes basically like this:

render: function () {
  $.tmpl(this.template, attrs).appendTo(this.el);
  return this;
},
         


        
5条回答
  •  一整个雨季
    2021-02-02 16:37

    I was facing a similar issue but in my case even the above solutions wouldn't work because the parent views hadn't been added to the DOM yet.

    Sticking with the convention of having the parent view add the children to the DOM, doing loadPlugins() in the render method didn't work.

    This is what I did. It feels kind of hacky but could help, depending on how you're managing your views throughout the hierarchy:

    render: function() {
      var self = this;
    
      setTimeout(function() {
        $(self.el).setupPlugin();
      }, 0);
    
      return this;
    }
    

    Using a setTimeout of 0 allows the current call stack to finish, so by the time the timeout function gets called the view and all it's parents have been added to the DOM. (If you stick to the convention mentioned above).

提交回复
热议问题