Reputation: 4161
I have been using backbone extensively in my application. I really like the event binding it gives me in model->views. I started my Javascript coding with backbone and I don't really know how to code without it.
I'm building another small application. I want to code it without using backbone. I have a view and a model associated with it. When model changes I'd like view to update. Currently in each method I'm doing it manually like this:
function updatesomething(){
//update model
model[something] = new updated value;
//update view
$(".something").addClass("updated value");
}
I would like to make this sophisticated by having pubsub type pattern where the view is listening for changes on model. How would I implement it in plain javascript without using backbone so that my code would look something like this:
function updatesomething(){
model.update(something);
}
//and view listening to this updates automatically
Upvotes: 2
Views: 95
Reputation: 16202
This is a great question, and one you should be asking. Developers reach for frameworks unthinkingly, like someone grabbing salt without tasting his food first. For many, many tasks even simple frameworks are overkill and can be replaced with vanilla js and basic OO patterns.
Here's a simple demo of the sub/pub pattern using vanilla js. You can use the mixin provided to make any of your plain js model object observable. You can then have your views subscribe to them and update on changes.
http://jsbin.com/umOhiFOP/1/edit
function makeObservable() {
this._subscribers = [];
this.subscribe = function(event, target, callback) {
this._subscribers.push({event:event, target:target, callback:callback});
}
this.trigger = function(event) {
this._subscribers.forEach(function(subscriber) {
if (event !== subscriber.event) return;
subscriber.callback.call(subscriber.target);
});
}
}
function Todo() {
this.isDone = false;
this.complete = function() {
this.isDone = true;
this.trigger('completed');
}
}
makeObservable.call(Todo.prototype);
function TodoSubscriber() {
this.onComplete = function() {
console.log('Todo completed');
}
}
var todo = new Todo();
var listener = new TodoSubscriber();
todo.subscribe('completed', listener, listener.onComplete);
todo.complete();
You might enjoy this article too: https://moot.it/blog/technology/riotjs-the-1kb-mvp-framework.html
Upvotes: 2