jquery - 在 Backbone 渲染方法中调用 jQuery 插件

标签 jquery jquery-plugins backbone.js

我在 Backbone 中有一个渲染方法,基本上是这样的:

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

从路由器操作中调用:

action: function () {
  $('#container').empty();
  $('#container').append(myView.render().el);
},

现在,我想在此 View 内的 label 元素上应用一个插件。我的第一个想法是在 render 中调用插件:

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

但这不起作用(我假设这是因为该元素尚未添加到 DOM 中)。如果我在路由器操作中调用插件,它确实可以工作:

action: function () {
  $('#container').empty();
  $('#container').append(myView.render().el);
  myView.$('label').inFieldLabels();
},

我不想这样做,因为插件是 View 的一部分,而不是路由器的一部分,所以在操作中调用它是没有意义的。有更好的方法吗?

最佳答案

最好这样做:

action: function () {
    var container = $('#container');

    container.empty();
    myView.render(container);
},

render: function (container) {
    $(this.el)
        .append($.tmpl(this.template, attrs))
        .appendTo(container);
    $('label', this.el).inFieldLabels();
    return this;
},

关于jquery - 在 Backbone 渲染方法中调用 jQuery 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7107904/

相关文章:

javascript - Backbone 形式:选择字段的样式选项?

javascript - Backbone.js 事件未触发

jquery - 使用 mootools 或 jquery 处理单击和拖动移动以水平滚动

Jquery Select2 插件版本检查

JQuery Cookie 在 Chrome 上不起作用

jquery - 在jquery中编写onclick事件的适当位置

inheritance - Backbone .js 模型继承

javascript - appendChild() 不适用于 Chrome。可能无法解释为 JavaScript

javascript - jquery验证错误

javascript - 多个DIV的翻转动画