Created
March 13, 2012 18:48
-
-
Save jotto/2030672 to your computer and use it in GitHub Desktop.
handling large forms in a 2-pane backbone.js app without re-painting the form elements
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
# returns an array of keys formatted like this | |
# blog[id] | |
# blog[title] | |
# blog[user_id] | |
# blog[admin][pageview] | |
# blog[admin][metrics][conversion_rate_last_30_days] | |
Backbone.Model.prototype.flatten_hash = (_attribs = this.attributes, _param_root = [this.paramRoot]) -> | |
_.flatten( | |
_(_attribs).map (v, k) => | |
if v? && typeof(v) == 'object' | |
return this.flatten_hash(v, _param_root.concat(k)).slice(0) | |
else | |
# base case | |
_root_param = _param_root[0] | |
_join_nested_params = _param_root.slice(1).map((v) -> "[#{v}]").join('') | |
return "#{_root_param}#{_join_nested_params}[#{k}]") | |
# gsubs the strings returned from flatten_hash into change events for Backbone | |
# blog[title] will change into "change:title" | |
# blog[admin][pageview] will change into "change:admin[pageview]" | |
# then triggers those events on the model | |
Backbone.Model.prototype.trigger_changes = -> | |
_(this.flatten_hash()).each (_string) => | |
_param_root_regex = new RegExp("#{this.paramRoot}") | |
this.trigger("change:#{_string.replace(_param_root_regex,'').replace(/\[/,'').replace(/\]/,'')}") | |
this.trigger("change") |
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
edit_blog: (id) -> | |
# render the left pane if it isn't already rendered | |
# this will execute if we load up an edit blog URL | |
this.left_pane() if !@left_pane? | |
window.model ||= new BlogModel({id: id}) | |
window.model.set({id: id}) | |
window.model.fetch | |
success: => | |
@blog_collection.add(new BlogModel(window.model.attributes)) if !@blog_collection.get(id) | |
if @right_pane | |
# trigger_changes() is a custom method that loops | |
# through each model attrib and triggers the "change:#{attrib_name}" event | |
@right_pane.model.trigger_changes() | |
else | |
@right_pane = new EditBlogView({model: window.model}).render() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment