F
F
Forum32014-11-13 15:37:01
JavaScript
Forum3, 2014-11-13 15:37:01

Javascript: Object Event Trapping Library ?

Good afternoon.
Recommend a library that allows you to simulate an event on objects and subscribe to them.
For example: we have an object, on / off / trigger methods are added to it, it calls trigger in the methods, and we catch it
. Sample syntax:

var newObject.prototype = {...}
newObject.extend(Events);

var test = new newObject();
test.on('событие', function() {
    // pass
})

There is something similar in underscore(extend) and Backbone(events), maybe someone knows such a library? You need a separate library, because. copy-paste or your bike is not welcome Used to assemble bower and grunt, and connecting Backbone is somehow not profitable in terms of resources

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
Elizaveta Borisova, 2014-11-13
@Elizaveta

Maybe something like this millermedeiros.github.io/js-signals

D
Denis Pushkarev, 2014-11-13
@rock

Write yourself. A dozen or two lines in the simplest implementation. From the finished, I don’t know why, eddy came to mind first .

T
Timur Shemsedinov, 2014-11-13
@MarcusAurelius

What's wrong with EventEmitter?

var events = require('events');
var test = new events.EventEmitter(); 
test.on('событие', function() {});
test.emit('событие');

S
Sergey Melnikov, 2014-11-13
@mlnkv

the simplest option:

function observable(el) {
    var callbacks = {}, slice = [].slice;

    el.on = function(events, fn) {
      if (typeof fn === "function") {
        events.replace(/\S+/g, function(name, pos) {
          (callbacks[name] = callbacks[name] || []).push(fn);
          fn.typed = pos > 0;
        });
      }
      return el;
    };

    el.off = function(events, fn) {
      if (events === "*") callbacks = {};
      else if (fn) {
        var arr = callbacks[events];
        for (var i = 0, cb; (cb = arr && arr[i]); ++i) {
          if (cb === fn) { arr.splice(i, 1); i--; }
        }
      } else {
        events.replace(/\S+/g, function(name) {
          callbacks[name] = [];
        });
      }
      return el;
    };

    // only single event supported
    el.one = function(name, fn) {
      if (fn) fn.one = true;
      return el.on(name, fn);
    };

    el.trigger = function(name) {
      var args = slice.call(arguments, 1),
        fns = callbacks[name] || [];

      for (var i = 0, fn; (fn = fns[i]); ++i) {
        if (!fn.busy) {
          fn.busy = true;
          fn.apply(el, fn.typed ? [name].concat(args) : args);
          if (fn.one) { fns.splice(i, 1); i--; }
          fn.busy = false;
        }
      }

      return el;
    };

    return el;
  };

var my_obj = {};
observable(my_obj);
my_obj.on("update", function() { /*  */ });
my_obj.trigger("update");

From here https://muut.com/riotjs/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question