RactiveJS和jQuery插件

use*_*067 9 jquery plugins ractivejs

我有一个包含多个字段的表单,其中一些用于纯文本,其中一些需要插件才能进行高级选择和上传功能.

这有两个问题:

  • ractive需要解析模板并在我附加插件之前渲染它,因此会有一些小的延迟
  • 第二个是这样的插件更改了所提到的字段周围的标记,并且无法使用ractive生成的DOM树,因为该标记不同步.

解决这个问题的正确方法是什么?我真的想使用ractive来绑定所有表单值并控制它的行为,但此时似乎几乎不可能.

Ric*_*ris 25

将jQuery插件与Ractive集成的好方法是使用装饰器.装饰器是一个元素进入DOM时被调用的函数; 它返回一个对象,该对象具有teardown()从DOM中删除时调用的方法.

因此,如果您使用的是jQuery File Upload插件,那么您的装饰器可能如下所示:

var fileupload = function (node) {
  $(node).fileupload();

  return {
    teardown: function () {
      $(node).fileupload('destroy');
    }
  };
};
Run Code Online (Sandbox Code Playgroud)

一旦你创建了装饰器,你需要注册它.最简单的方法是让它全球可用......

Ractive.decorators.fileupload = fileupload;
Run Code Online (Sandbox Code Playgroud)

...但您也可以传入每个实例或每个组件的装饰器:

// instance will have the fileupload decorator
ractive = new Ractive({
  // ...usual options...
  decorators: { fileupload: fileupload }
});

// all instances of Widget will have the decorator
Widget = Ractive.extend({
  decorators: { fileupload: fileupload }
});
Run Code Online (Sandbox Code Playgroud)

然后,您可以在模板中使用它,如下所示:

<input decorator="fileupload" type="file" data-url="whatever">
Run Code Online (Sandbox Code Playgroud)

碰巧使用此插件,您可以使用data-属性指定选项.但是如果你需要通过装饰器本身指定选项,你可以这样做:

<input decorator="fileupload:{{url}},{multiple:true}" type="file">
Run Code Online (Sandbox Code Playgroud)

在这个例子中,装饰器函数将接收另外两个参数 - 一个URL和一个options对象:

Ractive.decorators.fileupload = function (node, url, options) {
  // setup code...

  return {
    update: function (url, options) {
      // if the options change (i.e. `url` updates),
      // this function is called
    },
    teardown: function () {
      // teardown code...
    }
  };
};
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢你这个清晰简洁的解释.正是我希望找到的东西.这对我帮助很大. (3认同)