RactiveJS and jQuery plugins

橙三吉。 提交于 2019-11-28 19:50:57

A good way to integrate jQuery plugins with Ractive is to use decorators. A decorator is a function that gets called when an element enters the DOM; it returns an object with a teardown() method that is called when it's removed from the DOM.

So if you were using the jQuery File Upload plugin, your decorator might look like this:

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

  return {
    teardown: function () {
      $(node).fileupload('destroy');
    }
  };
};

Once you've created the decorator, you need to register it. The easiest way is to make it globally available...

Ractive.decorators.fileupload = fileupload;

...but you can also pass in per-instance or per-component decorators:

// 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 }
});

Then, you can use it in your template like so:

<input decorator="fileupload" type="file" data-url="whatever">

It so happens that with this plugin you can specify options with data- attributes. But if you needed to specify options via the decorator itself, you could do so:

<input decorator="fileupload:{{url}},{multiple:true}" type="file">

In this example, the decorator function would receive two additional arguments - a URL, and an options object:

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