Les Nightingill
Les Nightingill

Reputation: 6156

how to share behaviour between ractive components

Perhaps this is more of a basic javascript question than particular to Ractivejs.

How can I add shared behaviour to Ractive components... for example, if several components have a strip_whitspace() method, how can I avoid duplicating it in each component?

thanks in advance for any javascript or Ractivejs insight you can offer.

Upvotes: 2

Views: 164

Answers (2)

Bryan Ray
Bryan Ray

Reputation: 929

You can also look at Frequently Used Expressions in RactiveJS. If you use a particular expression frequently, you can add that expression to Ractive's default data, like so:

var helpers = Ractive.defaults.data;

helpers.fromNow = function(timeString){
  return moment(timeString).fromNow()
}

helpers.formatTime = function(timeString){
  return moment(timeString).format("ddd, h:mmA");
}

helpers.humanizeTime = function(timeString){
  return moment.duration(timeString).humanize();
}

Upvotes: 3

Joseph
Joseph

Reputation: 119837

The usual way to do it is to use extend, which pretty much looks like how you'd inherit in traditional OOP. Under the hood, it uses prototypal inheritance.

var CommonClass = Ractive.extend({
  // define common stuff
  strip_whitspace : function(){...}
});

var FirstClass = CommonClass.extend({
  // FirstClass stuff
});

var SecondClass = CommonClass.extend({
  // SecondClass stuff
});

If you prefer a more compositional approach where you build the object on the fly rather than impose inheritance, you can always use an extend function from other libs, like lodash's defaults. I prefer this method because I can inherit from more than one common object.

var UtilsMixin = {
  strip_whitspace : function(){...}
};

var AnotherMixin = {...};

var FirstClass = Ractive.extend(_.defaults({
  // FirstClass stuff
}, UtilsMixin));

var SecondClass = Ractive.extend(_.defaults({
  // SecondClass stuff
}, UtilsMixin, AnotherMixin));

Upvotes: 4

Related Questions