Last active
August 5, 2016 14:36
-
-
Save adamsilver/50b0bb62a118e0f651cea10bdd8f9f50 to your computer and use it in GitHub Desktop.
Delegation across different Javascript Objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var JournalEntryView = function(container) { | |
this.container = container; | |
} | |
JournalEntryView.prototype.onReplyButtonClicked = function(e) { | |
e.preventDefault(); | |
// ... | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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