Calling a jQuery plugin in a Backbone render method

前端 未结 5 1743
隐瞒了意图╮
隐瞒了意图╮ 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:45

    I've 'solved' this problem by adding a loadPlugins method to my view, so I can do myView.loadPlugins() after rendering in the action. It's not ideal, but it works.


    Edit: Well, I've heard from the horse's mouth and it looks like I can't apply the plugin before the element's been added to the DOM, so either I can do as above (with loadPlugins) or I can modify the code so the element gets added to the DOM in the render method. Hope this helps someone in a similar position.

    Here's how I'm doing it now:

    //in router
    action: function () {
      var myView = new MyView({
        el: '#container'
      });
    }
    
    //in view
    render: function () {
      $.tmpl(this.template, attrs).appendTo(this.el); //this now appends to the DOM
      this.loadPlugins();
      return this;
    },
    
    loadPlugins: function () {
      this.$('label').inFieldLabels();
      //and other plugins
    },
    

提交回复
热议问题