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
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.
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.
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.
- 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.
- 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.
Angular is too huge, difficult to learn, and the DSL feels dirty (at least for me).