Search code examples
backbone.jscoffeescriptbackbone-views

Backbone.js read model attributes in initialize


In one of my view I need to recopy an attribute value into another attribute.

Here is the code in my code in coffeescript

class MyFactoryView extends Backbone.View

  initialize: ->
    @model.fetch reset: true
    @model.set('NewStatus', @model.get('CurrentStatus'))

This code throws an undefined exception when I call get.

But if I do a console.log @model, I can see the CurrentStatus in attributes.


Solution

  • As mu said, fetch is async and you only have access to the attributes once it's finished.

    class MyFactoryView extends Backbone.View
    
      initialize: ->
        @model.fetch 
          reset: true
          context: @
          success ->
            @model.set('NewStatus', @model.get('CurrentStatus'))
    

    For that specific line, it could be simpler to use the parse function of the model to initialise the NewStatus attribute on sync.

    For the console, take a look at this answer which explains that the console contains live references and doesn't copy anything.