关注Backbone JS和CoffeeScript教程,遇到问题

时间:2013-03-29 20:31:30

标签: backbone.js coffeescript

我正在关注本教程:http://adamjspooner.github.com/coffeescript-meet-backbonejs/

到目前为止一切正常,除非我到达最后一节(5)并实现“交换”功能。当发生这种情况时,我会返回“未定义”,而不是应该返回的内容。请参阅教程以了解应该发生的事情。

我发现代码没有差异。

我的如下:(在coffeescript中)

jQuery ->
    class Item extends Backbone.Model
        defaults:
            part1:'Hi'
            part2:'Backbone'

    class List extends Backbone.Collection
        model: Item

    class ItemView extends Backbone.View
        tagName: 'li'

        initialize: ->
            _.bindAll @

            @model.bind 'change', @render
            @model.bind 'remove', @unrender

        render: ->
            $(@el).html """
                <span>#{@model.get 'part1'} #{@model.get 'part2'}!</span>
                <span class="swap btn btn-warning">swap</span>
                <span class="delete btn btn-danger">delete</span>
            """
            console.log @model.get 'part 2'
            @

        unrender: ->
            $(@el).remove()

        swap: ->
            @model.set
                part1: @model.get "part 2"
                part2: @model.get "part 1"

        remove: -> 
            @model.destroy()

        events:
            'click .swap' : 'swap'
            'click .delete' : 'remove'

    class ListView extends Backbone.View
        el: $ 'body'

        initialize: ->
            _.bindAll @

            @collection = new List
            @collection.bind 'add', @appendItem

            @counter = 0
            @render()

        render: ->
            $(@el).append "<button class='btn'>Add List Item</button>"
            $(@el).append "<ul></ul>"

        addItem: ->
            @counter++
            item = new Item
            item.set part2: "#{item.get 'part2'} #{@counter}"
            @collection.add item

        appendItem: (item) ->
            item_view = new ItemView model: item
            $('ul').append item_view.render().el

        events: 'click button' : 'addItem'

    Backbone.sync = (method, model, success, error) ->
        success()

    list_view = new ListView

HTML是:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Backbone App</title>
    <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
</head>
<body>
    <div class="content"></div>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.10/backbone-min.js"></script>
    <script src="app.js"></script>
</body>
</html>

我为我问这个问题的方式道歉,当我点击项目的交换按钮时,我无法弄清楚为什么它会返回“未定义”。找到这个问题将有助于我学习和理解Backbone JS。

1 个答案:

答案 0 :(得分:0)

下划线的bindAll现在不接受只有一个参数。您必须在bind中列出函数或传递参数:

@model.bind 'change', @render, this