Expected value not set when sync event fires in Backbone.Model

Asked 2 years ago, Updated 2 years ago, 40 views

In the combination of Backbone.js and Backbone.Marionette, the following code is written:

 varModel=Backbone.Model.extend({
    url: 'Any URL',

    dataFetch:function(){
        This.fetch()
            .fail(alert('error!!)'));
    }
});

varViewItem=Marionette.ViewItem.extend({
    model —new Model();
    modelEvents: {
        'sync': 'displayModelAttr'
    },

    initialize: function() {
        This.model.dataFetch();
    },

    displayModelAttr:function(){
        console.log(this.model.attributes);
    }
});

var viewItem = new ViewItem();

sync event that fired in model and attributes of model are displayed on the console.
However, an empty object is displayed instead of fetch from the url you specified.
When the sync event ignited, I thought that the model had fetch results to myself, but first of all, was it wrong to recognize it?

The communication itself has been successful and we have verified with the browser's development tool that the expected json has been returned.

javascript jquery backbone.js marionette

2022-09-30 16:18

1 Answers

I'm not sure if it's relevant because I can't reproduce the problem, but instead of specifying a model in Marionette.ItemView.extend, why don't you try specifying a model in the constructor like newViewItem({model:newModel()})?

The original code may not be expected because all ViewItems share a model.

When I tried using the code below, I found the values I got from the server as expected.
Changes from the code you are asking are indicated in the comments.

 varModel=Backbone.Model.extend({
    url: "/model.json",
    dataFetch:function(){
        This.fetch()
            .fail(function() {alert('error!!)') }); // Change to pass function to fail
    }
});

varViewItem=Marionette.ItemView.extend({//Marionette.ViewItem->Marionette.ItemView
    // If you specify a model here, all ViewItems will share one model.
    // Change the model to pass to the constructor
    // model —new Model(),
    modelEvents: {
        'sync': 'displayModelAttr'
    },

    initialize: function() {
        This.model.dataFetch();
    },

    displayModelAttr:function(){
        console.log(this.model.attributes);
    }
});

varviewItem = newViewItem({model:newModel()}); // Passes a different model for each ViewItem

Verification Environment:

  • jQuery 2.1.3
  • Undercore 1.6.0
  • Backbone 1.1.2
  • Marionette 2.3.1
  • Chrome39


2022-09-30 16:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.