Skip to content

Instantly share code, notes, and snippets.

@javisantana
Created November 28, 2014 11:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javisantana/0296ad726ec62f3b87e6 to your computer and use it in GitHub Desktop.
Save javisantana/0296ad726ec62f3b87e6 to your computer and use it in GitHub Desktop.

Backbone basics

4 elements to indetify

  • model / view
  • collection / view collection

model

  • all the stuff that goes to the server
  • operations on that data

collection

  • groups of models
  • operations that affect all the models
  • listen for events on all elements

view

  • view of a model
  • changes model ONLY on user actions
  • is modified by the model
  • it does NOT modify its own state

collection view

  • it shows the elements in the collection
  • it does NOT modify its own state
  • add/reset/remove

what not to DO

  • modify a model in a render method

  • modify a model in a render method

  • modify a model in a render method

  • no set, no save

  • never ever modify model.attributes

    _.update(model.attributes, {...}) // NO
    
  • never save a model on modification

  • never save a model on add/remove

  • modify a model in a render method, NEVER

models good practices

  • use parse to transform from the server to the client
parse: function(attrs) {
    this.my_sub_model.set(attrs.submodel)
    _.update(attrs, JSON.parse(attrs.options));
    delete attrs.options
    return attrs
}
  • toJSON to transform client side to server

views

  • if you are not sure about a method it probably goes in the model
    onUpdateBlah: function() {
        // this goes to the model
        var data = model.get('...');
        var o = ..
        for (var i in data) {
            o = fn(data[i])
        }
        // ~
        $el.html(data)
    }
  • don't leak bindings (add_related_model/addView)
  • if you are not able to change something in view only changing a model -> probably wrong
  • if you are not able to remove/add elements to a list from a collection -> wrong
  • render methods:
$el.html(...)
$el.find('...').html(...') //NO
// render offline
var el = $(....)
el.find('...').html(...') 

// render to the element
$el.html(el)
  • if you do operations with jquery -> probably really wrong

    • FUCK TIPSY
  • if you do $('.whatever') you are doing it really wrong

    • this.$('.whaever')
  • views does not know anything about its parent

general

  • DRY, spend 1 hours refactoring
  • think and try to use existing code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment