Client – server event aggregation with Vue

I have ment to look into Vue for a long time. Finally I took my time and fell in love right away. The simplicity and modularity is just great. I also saw how easy you can extend it so I decided to implement a plugin for my SignalR event aggregation library.

Plugins in Vue

Its really easy to create plugins with Vue. You just declare a function like

MyPlugin.install = function (Vue, options) {

   // inject some component options
  Vue.mixin({
    destroyed: function () {
      // some logic ...
    }
    ...
  })

  // add an instance method
  Vue.prototype.$myMethod = function (methodOptions) {
    // some logic ...
  }
}

And then install with Vue using

Vue.use(MyPlugin); 

Whats nice is that the component/viewmodel instance is kept over my plugin and the vm using it, so marshaling the object context (typically the this keyword) is really easy. This is really nice since then I can hide the context from the user. With destroyed function I can even call the vanilla libraries unsubscribe function so that the user does not need to think about this.

Using the plugin

new Vue({
    el: '#app',
    data: {
        events: []
    },
    created: function() {
        this.subscribe(MyApp.MyEvent, this.onEvent);        
    },
    methods: {
        onEvent: function(e) {
            this.events.push(e);
        }
    }
});

Above I have declared a Vue vm and from the created method I call subscribe which will hook up the server side event and the onEvent method will fire whenever a server side event is fired.

Source code

(function (signalR, vue) {
    signalR.install = function (vue) {
        vue.mixin({
            destroyed: function () {
                signalR.eventAggregator.unsubscribe(this);
            }
        });

        vue.prototype.subscribe = function (type, handler, constraint) {
            signalR.eventAggregator.subscribe(type, handler, this, constraint);
        };

        vue.prototype.publish = function (event) {
            signalR.eventAggregator.publish(event);
        };
    };
})(signalR || {}, Vue);

Here you can see the beauty of Vue, just a few lines of code for a wrapper like this. First I hook up to the destroyed function so that I can unsubscribe the context and its listeners. I also add two methods subscribe and publish. As you can see I can hide the context from the user by using this from the prototype function.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s