Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

This is translated from the original blog post written by @mizchi in Japanese:

データバインディングについてVue.jsと Backbone.stickitを比較する


This is part of the material to convince my company to use Vue.js instead of Backbone.stickit, so I will be picking on Backbone.stickit a bit :D

Comparing Backbone.stickit and Vue.js

The following example code basically implements "when the user clicks #menu, move the DOM to the left by 100 pixels".
The template function is simply a jade template exapander.

Backbone.stickit implementation

class MenuView extends Backbone.View
  initialize: ->
    @model = new Backbone.Model()
    @render()

  render: ->
    @$el.html template("""
      #menu.js-open
    """)
    @stickit()

  bindings:
    '.js-move':
      observe: 'positionX'
      update: ($el, model, val) ->
        $el.css 'left', val

Testing

it 'should move to left 100', ->
  menu = new MenuView
  menu.move()
  expect(menu.model.get 'positionX').eq 100

Problems

  • Backbone.stickit's observation syntax is DOM-centered
  • Depends on 'on chagnge' of Backbone.Model, so it can't handle nested model (common problem of Backbone.Model)
  • Manual, procedural code is required to wire up the view and model. This opens up window for buggy code.
  • jQuery in binding update handler is free and controllable for user but also can make the code bug-prone.

Vue.js implementation

Menu = Vue.extend
  template:
    template """
      #menu(v-style="left: positionX + 'px'" v-on="click: move")
    """
  data:
    positionX: 0
  methods:
    move: ->
      @$data.positonX = 100

testings

it 'should move to left 100', ->
  menu = new Menu
  menu.move()
  expect(menu.$data.positionX).eq 100

In this case, menu.$data correspond to Backbone.View's model and Vue's view is under controll by Vue's ViewModel. It hides the view control details from the user.

Merits

  • Fewer steps, stateful and declarative, not procedural
  • ViewModel hides unecessary details from the user
  • Template is intuitive and self-explanatory

The view becomes hidden and controllable through the manipulation of pure javascript objects. We can also avoid direct DOM manipulations.

I have never been able to write view logic code that is completely separated from the DOM before. I think such cohesiveness is important for front-end development.

My Thoughts

  • Hidden view controlled by the ViewModel is good.
  • Backbone.Model's get/set syntax is verbose and adds an extra layer of abstration. I don't want to treat the data as something special in order to make it reactive and bindable.

Comparing with Angular

Angular is too huge, difficult to learn, and the DSL feels dirty (at least for me).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment