Skip to content

Instantly share code, notes, and snippets.

@adamsilver
Last active August 5, 2016 14:36
Show Gist options
  • Save adamsilver/50b0bb62a118e0f651cea10bdd8f9f50 to your computer and use it in GitHub Desktop.
Save adamsilver/50b0bb62a118e0f651cea10bdd8f9f50 to your computer and use it in GitHub Desktop.
Delegation across different Javascript Objects
var JournalEntryView = function(container) {
this.container = container;
}
JournalEntryView.prototype.onReplyButtonClicked = function(e) {
e.preventDefault();
// ...
};
var JournalView = function(container) {
this.container = container;
this.container.on('click', '.reply-button', $.proxy(this, 'onReplyButtonClicked'));
this.createJournalEntryViews();
}
JournalView.prototype.onReplyButtonClicked = function(e) {
// work out which sub view to call the method on
var viewId = this.getIdFromTarget(e.currentTarget);
var view = this.subViews[viewId];
view.onReplyButtonClicked(e);
};
JournalView.prototype.getIdFromTarget = function (target) {
return parseInt(target.parents("[data-journal-entry-id']").getAttribute("data-journal-entry-id"), 10);
};
JournalView.prototype.createSubViews = function() {
this.subViews = {};
this.container.find('.journal-entry').each($.proxy(this, 'createSubView'));
};
JournalView.prototype.createSubView = function(i, el) {
this.subViews[el.getAttribute('data-journal-entry-id')] = new SubView($(el));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment